在一個簡單的Objective-C方法,我要創建對象的臨時數組,其中每個對象包含兩個元素:如何創建包含NSString和整數的臨時對象數組?
{
NSString *objectName;
int objectCount;
}
這是成爲一個臨時數組,而不是方法外使用,並沒有在對象接口中定義。如何在Objective-C中定義這樣的數組?
在一個簡單的Objective-C方法,我要創建對象的臨時數組,其中每個對象包含兩個元素:如何創建包含NSString和整數的臨時對象數組?
{
NSString *objectName;
int objectCount;
}
這是成爲一個臨時數組,而不是方法外使用,並沒有在對象接口中定義。如何在Objective-C中定義這樣的數組?
我會簡單地定義一個輔助對象:
@interface MyHelper
@property(copy) NSString *name;
@property(assign) unsigned int count;
@end
@implementation MyHelper
@end
就是這樣。如果您不使用ARC,則需要實施dealloc
以免費name
。
你也可以使用數組的數組(非常糟糕)或可變字典數組(也是不好的)。我不會推薦走這條路線,因爲它不僅僅是定義幫助對象,而且你失去了上下文。訪問第一個對象的名稱可能如下所示:
id element = [myArray objectAtIndex:0];
// Helper object
name = element.name; // or [element name]
// Array of arrays
name = [element objectAtIndex:0]; // 0 means "name"... ugh
// Array of dictionaries
name = [element objectForKey:@"name"]; // better than with arrays.
因此讀取名稱或計數很容易。但是當你想更新某些東西時,事情會變得混亂:
id element = [myArray objectAtIndex:0];
// Helper object
element.count++; // Easy. Everybody gets it.
// Array of arrays.
// Yuck!
NSNumber *oldValue = [element objectAtIndex:1];
[myArray replaceObjectAtIndex:0 withObject: @[ [element objectAtIndex:0], @([oldValue unsignedIntValue] + 1) ]];
// Or, if the element is actually a mutable array:
[element replaceObjectAtIndex:1 withObject: @([oldValue unsignedIntValue] + 1)];
// Array of MUTABLE dictionaries
// Better, but still ugly.
oldValue = [element objectForKey:@"count"];
[element setObject:@([oldValue unsignedIntValue] + 1) forKey:@"count"];
您可以將它添加到類擴展在.m文件,這樣的事情:
@interface YOURCLASSNAME()
@property (nonatomic, strong) NSArray *tmpArray;
@end
如果你要調用的事:
self.tempArray = ...
或
_tempArray = ...
或者您可以將其添加爲.ar文件中的ivar,如下所示:
@implementation YOURCLASSNAME {
NSArray *_tmpArray;
}
而且你怎麼稱呼它那樣:
_tempArray = ...
//擴展
要添加對象的數組,你可以這樣做:
CustomObject *obj1 = [[CustomObject alloc] init];
obj1.objectName = @"Name 1";
obj1.objectCount = 1;
CustomObject *obj2 = [[CustomObject alloc] init];
obj2.objectName = @"Name 2";
obj2.objectCount = 2;
_tmpArray = @[obj1, obj2];
請原諒我的無知,但這樣做的語法是什麼?正如你所看到的,我在這裏的基礎知識中掙扎了一番。我的意思是,一旦我聲明_tmpArray,我如何將int和string對象添加到它?我是否需要創建另一個包含這兩個元素的數組,然後將該數組添加到tmpArray? –
@SillyGoof(1)使它成爲一個NSMutableArray,而不是一個NSArray。看看NSMutableArray的文檔。 (2)不能將int對象添加到NSArray(或NSDictionary)中:int不是對象類型。你將不得不包裝在一個NSNumber對象中。 – matt
查看編輯答案,這是如何將自定義對象添加到數組。 – Greg
如果你不想創建一個自定義對象來存儲objectName和objectCount,你可以使用NSDictionary。
例子:
NSString *objectNameKey = @"objectName";
NSString *objectCountKey = @"objectCount";
NSDictionary *tempObject = [[NSDictionary dictionaryWithObjectsAndKeys:
@"someName", objectNameKey,
[NSNumber numberWithInteger:7], objectCountKey,
nil];
NSString *objectName = [tempObject objectForKey:objectNameKey];
int objectCount = [tempObject objectForKey:objectCountKey];
NSMutableArray * myarray = [NSMutableArray array]; – Merlevede