在Objective C中从整数制作指针

编程入门 行业动态 更新时间:2024-10-28 03:19:03
本文介绍了在Objective C中从整数制作指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

在使用 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;
}

我的问题是:

如何消除上述警告?除了在 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-24 12:37:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1063917.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   指针   Objective

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!