NSArray Overview for iOS Development | Generated by AI
What is NSArray?
NSArray is a class in Apple’s Foundation framework, part of the iOS SDK (and macOS, etc.). It represents an immutable, ordered collection of objects, similar to an array in other languages. This means once you create an NSArray, you can’t add, remove, or replace elements—you can only read from it. It’s commonly used in Objective-C for iOS app development to store and manage lists of data, like user preferences, database query results, or UI elements.
Key features:
- Immutable: Fixed size and contents after creation (use
NSMutableArrayfor mutable versions). - Type-safe for objects: Stores pointers to Objective-C objects (e.g.,
NSString,NSNumber, custom classes). It doesn’t support primitives directly—wrap them inNSNumberor similar. - Indexed access: Elements are accessed by integer index (0-based).
- Thread-safe: Generally safe for concurrent reads, but not writes (since it’s immutable).
- Integration: Works seamlessly with other Foundation classes like
NSDictionary,NSString, and Cocoa Touch UI components.
In Swift, NSArray is bridged to Array, but if you’re working in Objective-C (common for legacy iOS code), you’ll use NSArray directly.
How to Use NSArray in iOS
To use NSArray in an iOS project:
- Import the Foundation framework (it’s usually included by default in iOS apps).
#import <Foundation/Foundation.h> - Creating an NSArray:
- Literal syntax (iOS 6+):
@[object1, object2, ...] - Init method:
[[NSArray alloc] initWithObjects:object1, object2, nil] - From a C array:
initWithArray:copyItems:
Example:
NSArray *fruits = @[@"apple", @"banana", @"cherry"]; // Or: NSArray *numbers = [[NSArray alloc] initWithObjects:@1, @2, @3, nil]; - Literal syntax (iOS 6+):
- Accessing Elements:
objectAtIndex:for getting an item.countfor length.firstObject/lastObjectfor edges.containsObject:to check existence.
Example:
NSString *firstFruit = [fruits objectAtIndex:0]; // "apple" NSUInteger count = [fruits count]; // 3 BOOL hasOrange = [fruits containsObject:@"orange"]; // NO - Iterating:
- Fast enumeration:
for (id obj in array) { ... } enumerateObjectsUsingBlock:for block-based iteration (iOS 4+).
Example:
for (NSString *fruit in fruits) { NSLog(@"Fruit: %@", fruit); } - Fast enumeration:
- Common Operations:
- Sorting:
sortedArrayUsingSelector:orsortedArrayUsingComparator:. - Filtering:
filteredArrayUsingPredicate:(with NSPredicate). - Joining:
componentsJoinedByString:for strings. - Writing to file:
writeToFile:atomically:.
Example (filtering):
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"length > 5"]; NSArray *longFruits = [fruits filteredArrayUsingPredicate:predicate]; // Results: @[@"banana", @"cherry"] - Sorting:
- In iOS Contexts:
- Table Views: Pass an
NSArraytoUITableView’s data source methods liketableView:numberOfRowsInSection:(viacount) andtableView:cellForRowAtIndexPath:(viaobjectAtIndex:). - User Defaults: Store/retrieve with
NSUserDefaults:[defaults setObject:array forKey:@"savedItems"];. - JSON Handling: Convert to/from
NSDatawithJSONObjectWithData:options:error:.
- Table Views: Pass an
For mutable needs (e.g., adding items dynamically), switch to NSMutableArray:
NSMutableArray *mutableFruits = [NSMutableArray arrayWithArray:fruits];
[mutableFruits addObject:@"date"];
Tips
- Always check for
nilor bounds to avoid crashes: UseobjectAtIndex:with index validation. - Performance: O(1) for access, O(n) for searches.
- Modern iOS: Consider Swift’s
Arrayfor new projects—it’s more type-safe.
NSArray Documentation
NSMutableArray Documentation