如何建立一个类并在目标c中使用它? [英] How to make a class and use it in objective c?

查看:120
本文介绍了如何建立一个类并在目标c中使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我是一个具有目标C编程的初学者,而我的简单类却遇到了问题.
我已经编写了一个具有三个属性的简单类,然后尝试使用它,但是我遇到了一个问题,似乎该类的对象根本没有引用,因此没有任何值.有人可以帮我吗?


班级代码:
1-city.h

Hi,

im a beginner with objective c programming, and i have problem with my simple class.
i have coded a simple class with three properties, and then i tried to use it but i am facing a problem which it seems that the object of that class does not reference at all and as a result does not hold any value. can anyone help me please?


The class code:
1-city.h

#import <Foundation/Foundation.h>

@interface City : NSObject{
    NSString *cityname;
    NSString *description;
    UIImage *cityPic;
}

@property (nonatomic,retain) NSString *cityName;
@property (nonatomic,retain) NSString *description;
@property (nonatomic,retain) UIImage *cityPic;

@end



2- city.m



2- city.m

#import "City.h"

@implementation City:NSObject
@synthesize cityName;
@synthesize description;
@synthesize cityPic;

@end



3-对象的定义和使用



3- the object definition and use

- (void)viewDidLoad
{
       
   City *thiscity; 
    
    thiscity.cityName=@"London";
    thiscity.description=@"Capital of Britain";
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:thiscity.cityName message:thiscity.description delegate:self cancelButtonTitle:nil otherButtonTitles:@"ok", nil];
    [alert show];
    [super viewDidLoad];
	
}



输出为空警报.



The output is an empty alert.

推荐答案

您尚未初始化thiscity.

添加:
You have not initialized thiscity.

Add:
City *thiscity = [[City alloc] init];



在目标C中,未初始化的变量被初始化为零或Null.

因此,您的指针开始为null.

这样做时不会出现错误:



In Objective C, uninitialized variables are initialized to zero or Null.

So your pointer starts out as null.

You don''t get an error when you do:

thiscity.cityName = @"London";
thiscity.description = @"Capital of Britain";



因为属性.运算符只是以下方面的语法糖:



Because for properties the . operator is just syntactic sugar for:

[thiscity setCityName: @"London"];
[thiscity setDescription: @"Capital of Britain"];



并且在目标C中,您可以将任何消息发送至空对象-它只是悄悄地返回空值.

同样,当访问属性时,会将getCityName发送到Null并返回null.

因此,您最终得到一个空白警报.



And in Objective C, you can send any message you want to a null object -- it just quietly returns null.

Similarly when you are accessing the properties, you are sending getCityName to Null and getting back null.

So you end up with a blank alert.


这篇关于如何建立一个类并在目标c中使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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