无法访问返回对象的属性?

时间:2011-08-29 10:17:03

标签: objective-c

//SomeObject.h
#import <Foundation/Foundation.h>


@interface SomeObject : NSObject {

}
@property NSInteger aProperty;
@end

//main.m

#import <Foundation/Foundation.h>
#import "SomeObject.h"

int main (int argc, const char * argv[])
{

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    [dictionary setObject:[[[SomeObject alloc] init] autorelease] forKey:@"key1"];
    [dictionary setObject:[[[SomeObject alloc] init] autorelease] forKey:@"key2"];
    [dictionary objectForKey:@"key1"].aProperty = 5; //Error HERE
    [dictionary release];

    [pool drain];
    return 0;
}

但是在那一行XCode给了我这些错误:

error: Semantic Issue: Member reference type 'struct objc_object *' is a pointer; maybe you meant to use '->'?
error: Semantic Issue: No member named 'aProperty' in 'struct objc_object'

我无法访问返回对象的属性吗? (我的意思是,没有直接调用setter方法)

1 个答案:

答案 0 :(得分:1)

您需要强制转换返回的对象:

((SomeObject*)[dictionary objectForKey:@"key1"]).aProperty = 5;

或:

[(SomeObject*)[dictionary objectForKey:@"key1"] setAProperty: 5];

或:

SomeObject* obj = [dictionary objectForKey:@"key1"];
obj.aProperty = 5;
相关问题