Reputation: 6377
In my aplication, I have an nsmutablearray which stores a number of types of objects. All these objects are having two similar properties: id, type.
What I'm doing is I'm fetching the current working object in a 1-element array and accessing its properties id, type from within another class. This class is not aware which type of an object is the current object. How shall I access this object?
I tried doing:
commentId = [[appDelegate.currentDeailedObject valueForKey:@"id"] intValue];
commentType = [appDelegate.currentDeailedObject valueForKey:@"type"];
But it didn't work.
I created an object of type id like this:
id *anObject = [appDelegate.currentDeailedObject objectAtIndex:0];
commentId = [[anObject valueForKey:@"id"] intValue];
commentType = [anObject valueForKey:@"type"];
But it shows me 2 warnings: 1.warning: initialization from incompatible pointer type
2.warning: invalid receiver type 'id*'
How shall I make this work?
Thanx in advance.
Upvotes: 1
Views: 1199
Reputation: 14235
Correction for your code:
id anObject = [appDelegate.currentDeailedObject objectAtIndex:0];
int commentId = [anObject id];
NSString *commentType = [anObject type];
Notice the missing "*" after "id" (id already represents a reference) and the missing "valueForKey" (this is a method inside NSDictionary that returns a value that is represented by the provided key).
In general, this code should work,
But I'd suggest you to create a superclass or protocol that will have the 2 methods that you need (e.g. "id" and "type").
For example (superclass):
@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
Another example (protocol):
@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
Upvotes: 1
Reputation: 96937
Generic id
variables do not generally take a pointer assignment, because it is already a pointer. So you should use something like:
id anObject = [appDelegate.currentDeailedObject objectAtIndex:0];
You may want to use casts for commentId
and commentType
, e.g. (NSNumber *)
, etc.
Upvotes: 0