在Objective C中从整数制作指针 [英] Making pointer from integer in Objective C

查看:14
本文介绍了在Objective C中从整数制作指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

After programming with C# and Java for many years I finally decided to learn Objective-C in order to start programming iOS Devices as well as Mac OS X, and I have to admit it is very different then most modern c-based programming languages. I am getting the following warning in my code:

警告:传递SetAge"的参数 1 会使指针从整数而不进行强制转换

warning: passing argument 1 of 'SetAge' makes pointer from integer without a cast

这是我的代码:

狗.h

#import <Cocoa/Cocoa.h>


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

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

@end

狗.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

HelloWorld.m

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;
}

我的问题是:

  1. 如何消除上述警告?
  2. 除了在 Dog 类中创建设置 Age 和 Name 的方法之外,我如何才能让 Age 和 Name 公共类级别的变量可以直接分配给它?

任何帮助将不胜感激!

谢谢,皮特

推荐答案

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

Don't declare an int as a pointer. Change your code from:

- (void) SetAge: (int *) liAge

- (void) SetAge: (int) liAge

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

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

考虑创建年龄并命名属性.更改:

Consider making age and name a property. Change:

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

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

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

Also, don't forget to synthesize them in your implementation file:

@synthesize age, name;

这篇关于在Objective C中从整数制作指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆