views:

34

answers:

2

Hi all,

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.

A: 

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.

Alex Reynolds
Thanx Alex.. I did the same and it just worked..
neha
+1  A: 

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
Michael Kessler
Thanx for the detailed answer. It got solved by the first method.
neha