2011-09-30 109 views
0

想要创建实例化对象的方法。实例化对象的方法

- (NSArray *) make3Of : (Class) type 
{ 
    ... 
    type * temp = [[type alloc] ... 
    ... 
} 

但我得到的Xcode警告...

实际警告: “类方法+页头未找到(返回类型默认为‘身份证’)”

有没有更好的/正确的方式来做到这一点?

实际代码:

- (NSArray *) getBoxesOfType: (Class <ConcreteBox>) type StartingFrom: (uint64_t) offset 
{ 
    NSMutableArray *valueArray = [[NSMutableArray alloc]initWithObjects: nil]; 

    for (uint64_t i = offset; i< boxStartFileOffset + self.size; i += [self read_U32_AtBoxOffset:i]) 
    { 
     if ([[self read_String_OfLen:4 AtBoxOffset:offset + 4] isEqual:[type typecode]]) { 

      [[type alloc]initWithFile:file withStartOffset:i]; //warning here; 

      //yes I plan to assign it to a variable 
      //(originally of "type" but that won't work as AliSoftware pointed out, will be using "id" instead. 

      ... 

     } 
    } 
} 

与实例,我试图实例化一个连接对象。

代码协议:

#import <Foundation/Foundation.h> 

@protocol ConcreteBox 

+ (NSString *) typecode; 

- (id) initWithFile: (NSFileHandle *) aFile withStartOffset: (uint64_t) theOffset; 

@end 
+0

的问题是没有多少明确的。请给出实际的代码,应该有助于理解问题。 – objectivecdeveloper

+0

添加实际代码。 – WanderingInLimbo

+0

我没有看到你提供的问题。你能提供实际的班级定义吗?如果可能的话,你会得到实际的错误吗? –

回答

2

不能使用一个变量(在你的情况type)...作为一个类型,另一个变量!

在您的代码中,typetemp都是变量,这是一个语法错误。

由于您不知道编译时变量的类型,请改用动态类型id。这种类型专门用于处理在编译时未定义类型的情况。

所以,你的代码看起来就像这样:

-(NSArray*)make3Of:(Class)type { 
    id obj1 = [[[type alloc] init] autorelease]; 
    id obj2 = [[[type alloc] init] autorelease]; 
    id obj3 = [[[type alloc] init] autorelease]; 
    return [NSArray arrayWithObjects:obj1, obj2, obj3, nil]; 
} 
+0

谢谢。你是正确的使用“类型”作为变量声明的类型 - 但我其实还没有写入该部分; '[alloc alloc]'已经给我带来麻烦了。但是,这仍然没有解决“类方法+未找到alloc(返回类型默认为'id')”警告。 – WanderingInLimbo

+0

刚刚在Xcode中尝试了我在上面的答案中提供的确切代码,并且在此处没有提示。你可以说得更详细点吗? – AliSoftware

+0

嗯,你是对的。看来只有在涉及协议时才会出现警告。 '(类)'。我已经将实际的代码粘贴到问题中了 - 应该是最初完成的,但是我是通过智能手机发布的。 – WanderingInLimbo