如何创建临时对象数组,其中包含NSString和整数?

时间:2014-02-23 17:23:54

标签: objective-c arrays

在一个简单的Objective-C方法中,我想创建一个临时的对象数组,其中每个对象都包含两个元素:

{
    NSString *objectName;
    int objectCount;
}

这是一个临时数组,不在方法之外使用,也不在对象接口中定义。如何在Objective-C中定义这样的数组?

3 个答案:

答案 0 :(得分:2)

如果您不想创建存储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];

答案 1 :(得分:0)

您可以将它添加到.m文件中的类扩展名中,类似于:

@interface YOURCLASSNAME ()
@property (nonatomic, strong) NSArray *tmpArray;
@end

如果你想打电话就是:

self.tempArray = ...

_tempArray = ...

或者您可以将其添加为.m文件中的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];

答案 2 :(得分:0)

我只是定义一个辅助对象:

@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"];