简体   繁体   English

为什么不能使用对象初始化此NSArray?

[英]Why can I not initialize this NSArray With Objects?

I have an array containing objects of a custom-made class. 我有一个包含定制类对象的数组。 However, on initialization the compiler gives me an error - "Lexical or Preprocessor" Expected ':' 但是,在初始化时,编译器给我一个错误- "Lexical or Preprocessor" Expected ':'

interface myClass : NSObject
@property (readwrite, strong) NSString* name;
@property (readwrite, strong) NSString* home;
@property (readwrite, strong) Preference pref; // This is another custom class
-(id) initWithName:(NSString*) name home:(NSString*) home preference:(Preference) preference;
end

@interface MyViewController()
@property (nonatomic, strong) NSArray *rowArray;
@end

@implementation MyViewController
...
...
...

- (void) initializeArray
{
    self.rowArray = @{
                      [[myClass alloc] initWithName:@"Harry" home:@"New York" preference :Acura],
                      [[myClass alloc] initWithName:@"Win" home:@"Seattle" preference :Toyota];
                    };
}

Can someone tell me just where I am messing up and why I'm getting this error? 有人可以告诉我我在搞什么,为什么会收到此错误?

The Objective-C literal for an array is with square brackets, 数组的Objective-C文字带有方括号,

NSArray *anArray = @[obj1, obj2] . NSArray *anArray = @[obj1, obj2]

In the code you posted it is trying to make a Dictionary, 在您发布的代码中,它试图制作字典,

NSDictionary *aDict = @{"key1" : obj1, @"key2" : obj2}

so this is why it is saying it expects a : . 所以这就是为什么它说期望:

The line should read, 该行应显示为

self.rowArray = @[
    [[myClass alloc] initWithName:@"Harry" home:"New York" preference :Acura],
    [[myClass alloc] initWithName:@"Win" home:"Seattle" preference :Toyota];
];

As others have pointed out the there are a few other errors with the code and those city names are not NSString's, but I guess this is just an example snippet. 正如其他人指出的那样,该代码还有其他一些错误,并且这些城市名称不是NSString的,但是我想这只是一个示例片段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM