[英]Accessing properties of object in an nsmutablearray iphone sdk
在我的应用中,我有一个nsmutablearray,它存储许多类型的对象。 所有这些对象都具有两个相似的属性:id,type。
我正在做的是在一个1元素数组中获取当前的工作对象,并从另一个类中访问其属性ID和类型。 此类不知道当前对象是哪种类型的对象。 我应该如何访问该对象?
我试着做:
commentId = [[appDelegate.currentDeailedObject valueForKey:@"id"] intValue];
commentType = [appDelegate.currentDeailedObject valueForKey:@"type"];
但这没有用。
我创建了一个ID类型的对象,如下所示:
id *anObject = [appDelegate.currentDeailedObject objectAtIndex:0];
commentId = [[anObject valueForKey:@"id"] intValue];
commentType = [anObject valueForKey:@"type"];
但它向我显示2条警告:1.警告:从不兼容的指针类型进行初始化
2.警告:无效的接收者类型“ id *”
我该如何工作?
提前感谢。
更正您的代码:
id anObject = [appDelegate.currentDeailedObject objectAtIndex:0];
int commentId = [anObject id];
NSString *commentType = [anObject type];
请注意,在“ id”(id已经表示一个引用)之后缺少“ *”,在“ valueForKey”(这是NSDictionary内部的一种方法,该方法返回由提供的键表示的值)之后。
通常,此代码应该有效,
但我建议您创建一个超类或协议,该类将具有所需的2种方法(例如“ id”和“ type”)。
例如(超类):
@interface MyComment : NSObject
{
NSInteger commentId;
NSString *_commentType;
}
@property (nonatomic) NSInteger commentId;
@property (nonatomic, copy) NSString *commentType;
@end
@implementation MyComment
@synthesize commentId, commentType = _commentType;
- (void)dealloc {
[_commentType release];
[super dealloc];
}
@end
// sample use
@interface MyCommentNumberOne : MyComment
{
}
@end
另一个示例(协议):
@protocol CommentPropertiesProtocol
@required
- (NSInteger)commentId;
- (NSString *)commentType;
@end
// sample use
@interface MyCommentNumberOne : NSObject <CommentPropertiesProtocol>
{
NSInteger commentId;
NSString *_commentType;
}
@end
@implementation MyCommentNumberOne
- (NSInteger)commentId {
return commentId;
}
- (NSString *)commentType {
return _commentType;
}
- (void)dealloc {
[_commentType release];
[super dealloc];
}
@end
通用id
变量通常不进行指针分配,因为它已经是指针。 因此,您应该使用类似:
id anObject = [appDelegate.currentDeailedObject objectAtIndex:0];
您可能要对commentId
和commentType
使用强制commentId
commentType
,例如(NSNumber *)
等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.