我有两节课,Workout而且Action.Workout有一个名为的方法associateActionsAndCounts,它接收存储的NSString数据和NSInteger数据并Action为它们创建一个.现在Action该类具有我编写的工厂方法以使此方法更简单,但是当我尝试调用其中一个工厂方法时,Xcode告诉我"没有已知的选择器类的方法'initWithName:andCount`".
Action.h
#import <Foundation/Foundation.h>
@interface Action : NSObject
+(Action *)initWithName:(NSString*)name;
+(Action *)initWithName:(NSString*)name andCount:(NSInteger*)count;
+(Action *)initWithName:(NSString*)name andCount:(NSInteger*)count andImage:(UIImage*)image;
@property UIImage *image;
@property NSString *name;
@property NSInteger *count;
@end
Run Code Online (Sandbox Code Playgroud)
Action.m
#import "Action.h"
@implementation Action
@synthesize image;
@synthesize name;
@synthesize count;
#pragma mark - factory methods
+(Action *)initWithName:(NSString *)name {
Action *newAct = [Action alloc];
[newAct setName:name];
return newAct;
}
+(Action *)initWithName:(NSString*)name andCount:(NSInteger*)count {
Action *newAct = [Action alloc];
[newAct setName:name];
[newAct setCount:count];
return newAct;
}
+(Action *)initWithName:(NSString *)name andCount:(NSInteger *)count andImage:(UIImage *)image {
Action *newAct = [Action alloc];
[newAct setName:name];
[newAct setCount:count];
[newAct setImage:image];
return newAct;
}
@end
Run Code Online (Sandbox Code Playgroud)
锻炼.m - associateActionsAndCounts(动作和计数是ivars)
-(void)associateActionsAndCounts {
for (int i=0;i<actions.count;i++) {
NSString *name = [actions objectAtIndex:i];
NSString *num = [counts objectAtIndex:i];
Action *newAction = [Action initWithName:name andCount:num]; //no known class method for selector
[actionsData addObject:newAction];
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
与Michael Dautermann合作的建议,我的代码现在看起来像这样:
-(void)associateActionsAndCounts {
for (int i=0;i<actions.count;i++) {
NSString *actionName = [actions objectAtIndex:i];
NSInteger num = [[NSString stringWithString:[counts objectAtIndex:i]] intValue];
Action *newAction = [Action actionWithName:actionName andCount:num];
[actionsData addObject:newAction];
}
}
Run Code Online (Sandbox Code Playgroud)
Action.h
+(Action *)actionWithName:(NSString*)name;
+(Action *)actionWithName:(NSString*)name andCount:(NSInteger*)count;
+(Action *)actionWithName:(NSString*)name andCount:(NSInteger*)count andImage:(UIImage*)image;
Run Code Online (Sandbox Code Playgroud)
但我仍然得到同样的错误.
没有已知的选择器"actionWithName:andCount"的类方法
你这里有一些问题.
第一,num您andCount在代码中传入" "参数的参数是一个NSString对象,而不是NSInteger您声明的方法所期望的对象.
第二,如果您正在采用这种"工厂"方法,请不要将其命名为"initWithName: andCount: ",因为这意味着您希望在" alloc"之前使用" "方法init.用不同的名称声明它,例如" +(Action *) actionWithName: andCount:".否则,如果出现内存问题,那么在查看此代码时,您(或者更糟糕的是,不是您的另一个程序员)将会非常困惑.
| 归档时间: |
|
| 查看次数: |
217 次 |
| 最近记录: |