iPhone对象 - - 检索的NSMutableArray自定义对象 [英] iPhone Obj-C - Retrieve custom object from NSMutableArray
问题描述
有:
@interface MyClass的:NSObject的{
* NSString的名称; //保留并合成
* NSString的地址; //保留并合成
}
我创建一个数组:
的NSMutableArray * myArray的; //保留并合成
与几个MyClass的对象,加油吧:
MyClass的*吉= [MyClass的新]
kat.name = @somestring
kat.address = @someotherstring
[myArray的ADDOBJECT:吉]
[吉发行];
我怎样才能在一些指标得到对象呢?下面的code一直给我空,但它应该说明我需要什么。
MyClass的OBJ * =(MyClass的*)[myArray的objectAtIndex:5];
的NSLog(@选择:%@,obj.address); // = NULL :(
这是什么毛病铸造或我忘记了什么?
MyClass的OBJ * =(MyClass的*)[myArray的objectAtIndex:5];
的NSLog(@选择:%@,obj.address); // = NULL :(
如果是code是印刷(空)
,它的无法的是因为数组为空或 objectAtIndex:
失败。 objectAtIndex:
将引发一系列的异常,如果您尝试访问索引超出数组中的对象的数量和数组不能包含洞或零引用
这code会平安无事的唯一途径是,如果:
-
myArray的
是零;你没有分配和/或Array实例分配给myArray的
。 -
obj.address
返回零;您没有正确初始化实例(看来你做)。
Having:
@interface MyClass : NSObject {
NSString *name; // retained and synthesized
NSString *address; // retained and synthesized
}
I'm creating an array:
NSMutableArray *myArray; // retained and synthesized
Filling it with several MyClass objects:
MyClass *kat = [MyClass new];
kat.name = @"somestring";
kat.address = @"someotherstring"
[myArray addObject:kat];
[kat release];
How can I get object at some index? The code below keeps giving me null but it should illustrate what I need..
MyClass *obj = (MyClass*)[myArray objectAtIndex:5];
NSLog(@"Selected: %@", obj.address); // = null :(
Is it something wrong with casting or I'm forgetting about something?
MyClass *obj = (MyClass*)[myArray objectAtIndex:5];
NSLog(@"Selected: %@", obj.address); // = null :(
If that code is printing (null)
, it cannot be because the array is empty or objectAtIndex:
failed. objectAtIndex:
will throw a range exception if you try to access an index beyond the count of objects in the array and an array cannot contain "holes" or nil references.
The only way that code will run without incident is if:
myArray
is nil; you didn't allocate and/or assign an array instance tomyArray
.obj.address
returns nil; you didn't correctly initialize the instance (which it appears you did).
这篇关于iPhone对象 - - 检索的NSMutableArray自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!