iPhone Obj-C - 从 NSMutableArray 检索自定义对象
具有:
@interface MyClass : NSObject {
NSString *name; // retained and synthesized
NSString *address; // retained and synthesized
}
我正在创建一个数组:
NSMutableArray *myArray; // retained and synthesized
用几个 MyClass 对象填充它:
MyClass *kat = [MyClass new];
kat.name = @"somestring";
kat.address = @"someotherstring"
[myArray addObject:kat];
[kat release];
如何在某个索引处获取对象?下面的代码一直给我空值,但它应该说明我需要什么..
MyClass *obj = (MyClass*)[myArray objectAtIndex:5];
NSLog(@"Selected: %@", obj.address); // = null :(
是铸造有问题还是我忘记了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果该代码正在打印
(null)
,则不可能是因为数组为空或objectAtIndex:
失败。objectAtIndex:
如果您尝试访问超出数组中对象计数的索引,并且数组不能包含“空洞”或 nil 引用,则会引发范围异常。代码正常运行的唯一方法是:
myArray
为 nil;您没有为myArray
分配和/或分配数组实例。obj.address
返回 nil;您没有正确初始化实例(看起来您确实做到了)。If that code is printing
(null)
, it cannot be because the array is empty orobjectAtIndex:
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).仅在 @property/@synthesize 对中声明 myArray 是不够的。您还需要 myArray 为非零。你需要添加
myArray = [[NSMutableArray alloc] init];
在您的
[addObject:]
调用之上的某处。此外,由于您已将“myArray”变量声明为保留,因此如果您通过 self.myArray = otherArray 将另一个(非零)数组设置为 myArray,则 myArray 将是非零且保留并准备就绪接受物体。
另外,如果您分配了 myArray,请不要忘记在类的 dealloc 方法中释放它。
It's not enough to just declare myArray in an @property/@synthesize pair. You need myArray to be non-nil as well. You need to add
myArray = [[NSMutableArray alloc] init];
somewhere above your
[addObject:]
call.Additionally, since you've declared the "myArray" variable as retain, if you set another (non-nil) array to myArray through
self.myArray = otherArray
myArray will be non-nil and retained and ready to accept objects.Also, if you allocate myArray, don't forget to release it in your class's dealloc method.