在Objective C中从整数制作指针

Dig*_*dia 2 xcode objective-c

在使用C#和Java编程多年后,我终于决定学习Objective-C以开始编程iOS设备以及Mac OS X,我不得不承认它与大多数现代的基于c的编程语言非常不同.我在代码中收到以下警告:

警告:传递'SetAge'的参数1使得整数指针没有强制转换

这是我的代码:

Dog.h

#import <Cocoa/Cocoa.h>


@interface Dog : NSObject {
    int ciAge;
    NSString * csName;
}

- (void) Bark;
- (void) SetAge: (int *) liAge;
- (void) SetName: (NSString *) lsName;

@end
Run Code Online (Sandbox Code Playgroud)

Dog.m

#import "Dog.h"

@implementation Dog

- (void) Bark
{
    NSLog(@"The dog %@ barks with age %d", csName, ciAge);  
}

- (void) SetAge: (int *) liAge {
    ciAge = (int)liAge;
}

- (void) SetName: (NSString *) lsName {
    csName = lsName;
}
@end
Run Code Online (Sandbox Code Playgroud)

HelloWorld.m

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


int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    int liTemp = 75;
    NSString * lsCity = @"Chicago";
    NSDate * loDate = [NSDate date];

    // insert code here...
    NSLog(@"The temperature is %d currently in %@, on %@", liTemp, lsCity, loDate);

    int liAge = 10;

    // Call Dog class
    Dog * Dog1 = [Dog new];
    [Dog1 SetAge:(int)liAge]; // The Warning happens here
    [Dog1 SetName:@"Fido"];

    [Dog1 Bark];


    [pool drain];
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:

  1. 我如何摆脱上面的警告?
  2. 而不是在Dog Class中创建用于设置Age和Name的方法,我怎样才能使Age和Name公共类级变量可以直接分配给它?

任何帮助将非常感激!

谢谢,皮特

Jer*_*emy 9

不要将int声明为指针.更改您的代码:

- (void) SetAge: (int *) liAge
Run Code Online (Sandbox Code Playgroud)

- (void) SetAge: (int) liAge
Run Code Online (Sandbox Code Playgroud)

- (void) SetAge: (int *) liAge {
    ciAge = (int)liAge;
}
Run Code Online (Sandbox Code Playgroud)

- (void) SetAge: (int) liAge {
    ciAge = liAge;
}
Run Code Online (Sandbox Code Playgroud)

考虑制作年龄并命名属性.更改:

- (void) SetAge: (int *) liAge;
- (void) SetName: (NSString *) lsName;
Run Code Online (Sandbox Code Playgroud)

@property (nonatomic, readwrite) NSInteger age; //Don't declare as pointer
@property (nonatomic, retain) NSString *name; //DO declare as pointer
Run Code Online (Sandbox Code Playgroud)

另外,不要忘记在实现文件中合成它们:

@synthesize age, name;
Run Code Online (Sandbox Code Playgroud)

  • `NSString`属性应该使用`copy`而不是`retain`. (3认同)