本文通過Person模型類,演示NSArray與NSMutableArray的字面量創建、混合類型存儲、嵌套數組、模型對象存取、NSNumber包裝基本類型、查找與判斷包含等實戰技巧。
// Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) int age;
- (instancetype)initWithName:(NSString *)name andAge:(int)age;
- (NSString *)description; // 重寫描述,便於NSLog直接輸出對象
@end
// Person.m
#import "Person.h"
@implementation Person
- (instancetype)initWithName:(NSString *)name andAge:(int)age {
if (self = [super init]) {
_name = name; _age = age;
}
return self;
}
- (NSString *)description {
return [NSString stringWithFormat:@"名字%@ 年齡%d", _name, _age];
}
@end
NSArray *arr1 = @[@"one", @"two", @"three"];
NSArray *arr2 = @[@1, @2, @3]; // 自動包裝為NSNumber
NSNumber包裝int i = 10;
NSNumber *num = [NSNumber numberWithInt:i]; // 或 @(i)
NSArray *mixed = @[@"one", @"two", num];
NSNumber提供豐富工廠方法:numberWithInt:、numberWithDouble:、numberWithBool:、numberWithChar:等。
NSArray *a1 = @[@"one", @"two"];
NSArray *a2 = @[@1, @2];
NSArray *nested = @[a1, a2]; // 二維數組
Person *p1 = [[Person alloc] initWithName:@"jack" andAge:15];
Person *p2 = [[Person alloc] initWithName:@"tom" andAge:20];
NSArray *persons = @[p1, p2];
Person *p = persons[1]; // 等同于 [persons objectAtIndex:1]
NSLog(@"%@", p); // 輸出:名字tom 年齡20
NSArray *nums = @[@(8.99), @(3.1f), @(5), @('c')];
char c = [nums[3] charValue]; // 取char
NSLog(@"%c", c); // c
BOOL contains = [persons containsObject:p1]; // 指針地址比較
NSLog(@"%d", contains); // 1 (YES)
NSMutableArray *mArr = [NSMutableArray arrayWithArray:persons];
[mArr addObject:[[Person alloc] initWithName:@"new" andAge:25]];
[mArr removeObjectAtIndex:0];
[mArr insertObject:@"string" atIndex:1]; // 可混入非模型對象(不推薦)
#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
// 創建各類數組
NSArray *arr1 = @[@"one", @"two", @"three"];
NSArray *arr2 = @[@1, @2, @3];
NSArray *nested = @[arr1, arr2];
NSLog(@"nested: %@", nested);
// 模型數組
Person *p1 = [[Person alloc] initWithName:@"jack" andAge:15];
Person *p2 = [[Person alloc] initWithName:@"tom" andAge:20];
Person *p3 = [[Person alloc] initWithName:@"dick" andAge:16];
NSArray *persons = @[p1, p2, p3];
NSLog(@"persons: %@", persons);
// NSNumber包裝
NSArray *nums = @[@(8.99), @(3.1f), @(5), @('c')];
char c = [nums[3] charValue];
NSLog(@"char: %c", c);
// 訪問與查找
Person *p = persons[1];
NSLog(@"persons[1]: %@", p);
BOOL has = [persons containsObject:p1];
NSLog(@"contains p1: %d", has);
}
return 0;
}
@[...]創建不可變數組,需修改時再mutableCopy。NSNumber/NSValue包裝才能存入集合。description方法,調試輸出更直觀。containsObject:按指針地址判斷,若需按業務鍵(如ID)查找,請用indexOfObjectPassingTest:配合Block。熟練運用Foundation集合與模型對象交互,是構建清晰、健壯Objective-C應用的核心基本功。