2012-08-16 93 views
0

我想在运行时存储数据,我可以有一个链表并在运行时添加,但是因为我是IOS和目标C的新手,我们是否有任何默认列表可以添加我们的数据,(数据是两个刺和一个整数)。目标C中的默认列表?

回答

0

Cocoa提供了NSArrayNSMutableArray,一对类似于Java的ArrayList和C#的List的有序容器。您可以将值添加到NSMutableArray,并且它会随着添加更多元素而增加; NSArray是只读的。

+0

所以我要创建模式种类,并添加对象到NSMutableArray的右侧列表? – Newbee 2012-08-16 11:18:36

+0

您需要创建一个类,继承'NSObject',添加它可能需要的任何属性(例如两个字符串和一个整数),然后将此类的实例添加到您的'NSMutableArray'中。 – dasblinkenlight 2012-08-16 11:23:49

0

您可以使用NSArrayNSMutableArrayNSDictionaryNSMutableDictionary根据您的需要。

的NSArray:

NSArray *myArray; 
NSDate *aDate = [NSDate distantFuture]; 
NSValue *aValue = [NSNumber numberWithInt:5]; 
NSString *aString = @"a string"; 
myArray = [NSArray arrayWithObjects:aDate, aValue, aString, nil]; 

的NSMutableArray:

NSMutableArray *myArray = [[NSMutableArray alloc] init]; 
NSDate *aDate = [NSDate distantFuture]; 
NSValue *aValue = [NSNumber numberWithInt:5]; 
NSString *aString = @"a string"; 
[myArray addObject:aDate]; 
[myArray addObject:aValue]; 
[myArray addObject:aString]; 

的NSDictionary:

NSDictionary * myDict = [NSDictionary dictionaryWithObjects:aDate, aValue, aString forKeys:firstDate, firstValue, firstString]; 

的NSMutableDictionary:

NSString *aString = @"a string"; 
NSDate *aDate = [NSDate distantFuture]; 
NSValue *aValue = [NSNumber numberWithInt:5]; 
myDict = [[NSMutableDictionary alloc] init]; 
[myDict setObject:aString forKey:firstString]; 
[myDict setObject:aDate forKey:firstDate]; 
[myDict setObject:aValue forKey:firstValue]; 
+0

为什么额外保留在'[[[[NSMutableDictionary alloc] init] retain];''alloc已经保留。这可能会导致代码泄漏。 – rckoenes 2012-08-16 11:29:43

+0

对不起,只是一种习惯。编辑。 – hockeyman 2012-08-16 11:32:41

0

使用默认属性为您的数据创建一个类,并确保它继承NSObject,然后使用NSMUtableArray将元素添加到列表中。

// in the .h file of your object 
@interface MyObject : NSObject { 
    NSString* strAttribute1; 
    // add more attributes as you want 
} 

@property (nonatomic, retain) NSString* strAttribute1; 

@end 

// then in the .m file 
// do not forget the #import "" 
@implement MyObject 
@synthesize strAttribute1; 

// override the dealloc to release the retained objects 
@end 

然后在你的代码,你想使这个对象

NSMutableArray* myArray = [[NSMutableArray alloc] init]; 

// add elements and iterate through them 

// do not forgot to free the memory if you are not using ARC 
[myArray release]; 
+0

我正在尝试做同样的事情。 – Newbee 2012-08-16 11:20:52