Click here to Skip to main content
15,896,557 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
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
#import "City.h"

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

@end


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

1 solution

You have not initialized thiscity.

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


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"];


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.
 
Share this answer
 
Comments
Brainy Girl 7-Jun-12 11:30am    
Thank you so much, that was really helpful :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900