我有一个通过iPhone应用程序使用的用户类,这是我的用户类(NSobject的子类)中的init和initWithUser函数,当我使用initWithUser函数时,收到代码后描述的警告。请指教。
// serialize.h
#import <Foundation/Foundation.h>
@protocol Serialize
// serialize the object to an xml string
-(NSString*)ToXML;
@end
// user.h
#import <Foundation/Foundation.h>
#import "Serialize.h"
#import "Contact.h"
@interface User : NSObject <Serialize> {
NSString *email;
NSString *firstName;
NSString *lastName;
NSString *userId;
NSString *userName;
NSString *password;
NSMutableArray *contactList;
}
@property (nonatomic,copy) NSString *email;
@property (nonatomic,copy) NSString *firstName;
@property (nonatomic,copy) NSString *lastName;
@property (nonatomic,copy) NSString *userId;
@property (nonatomic,copy) NSString *userName;
@property (nonatomic,copy) NSString *password;
@property (nonatomic, retain) NSMutableArray *contactList;
//-(id)init;
-(id)initWithUser:(User *)copyUser;
@end
// user.m
#import "user.h"
@implementation User
@synthesize email;
@synthesize firstName;
@synthesize lastName;
@synthesize userId;
@synthesize userName;
@synthesize password;
@synthesize contactList;
-(id)init
{
// call init in parent and assign to self
if( (self = [super init]) )
{
// do something specific
contactList = [[NSMutableArray alloc] init];
}
return self;
}
-(id)initWithUser:(User *)copyUser
{
if( (self = [self init]) ) {
email = copyUser.email;
firstName = copyUser.firstName;
lastName = copyUser.lastName;
userId = copyUser.userId;
userName = copyUser.userName;
password = copyUser.password;
// release contactList initialized in the init
[contactList release];
contactList = [copyUser.contactList mutableCopy];
}
return self;
}
- (void)dealloc
{
// TODO:
[contactList removeAllObjects];
[contactList release];
[super dealloc];
}
// implementation of serialize protocol
-(NSString*)ToXML
{
return @"";
}
我这样在主控制器上使用它
- (void) registerNewUser {
RegistrationViewController *regController = [[RegistrationViewController alloc] init] ;
regController.newUser = [[User alloc] initWithUser:self.user];
[self.navigationController pushViewController:regController animated:YES];
[regController release];
}
线
regController.newUser = [[User alloc] initWithUser:self.user];
给我以下错误,并且让我发疯了几天。
不兼容的Objective-c类型'struct User *',当传递来自不同Objective-c类型的'initWithUser:'参数1时,预期为'struct NSString *'
任何帮助和指导表示赞赏
最佳答案
问题是您的选择器不明确。因为alloc
返回id
,所以对initWithUser:
的调用变得模棱两可。 NSUserDefaults
还有一个initWithUser:
函数,该函数采用字符串。编译器认为您正在尝试使用该代码。将行更改为
regController.newUser = [(User*)[User alloc] initWithUser:self.user];
一切都会按预期进行。