Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Mvkoe

macrumors regular
Original poster
Aug 4, 2008
103
3
Belgium
Hey

So I'm learning Objective-C with a Java background. It turns out quite good atm. I'm dutch and learning it with a English book. Sometimes I'm not understanding things, but that's why i'm asking it here!

In Java you have a Default Constructor, and you can edit the constructor like in the example.

Code:
	public Date (int day, int month, int year){
		setYear(day);
		setMonth(month);
		setDay(year);
	}

How is this handeled by Objective-C, anyone has an example for this ?

Further I know you can't really use get in your Getter methods because Cocoa would argue sometimes.

Code:
public class Date {

	private int year;
	private int month;
	private int day;
	
	public Date (){
		
	}
	
	public Date (int day, int month, int year){
		setYear(day);
		setMonth(month);
		setDay(year);
	}
	
	public void setYear(int year){
		
	}
	
	public void setMonth(int month){
		
	}
	
	public void setDay(int day){
		
	}
	
	public int getYear(){
	
	}
	
	public int getMonth(){
	
	}
	
	public int getDay(){
	
	}
}
 

mfram

Contributor
Jan 23, 2010
1,304
341
San Diego, CA USA
In Java you have a Default Constructor, and you can edit the constructor like in the example.

Code:
	public Date (int day, int month, int year){
		setYear(day);
		setMonth(month);
		setDay(year);
	}

How is this handeled by Objective-C, anyone has an example for this ?

There's no real concept of a "constructor" in Obj-C. Instead, the standard is to create initialization routines. Something like:

Code:
-(void)initWithDay:(int)day withMonth:(int)month withYear:(int)year;

Date *d = [[Date alloc] initWithDay:1 withMonth:1 withYear:2013];

Further I know you can't really use get in your Getter methods because Cocoa would argue sometimes.

Code:
	public void setYear(int year){	
	}
	
	public int getYear(){
	}
}

Use @property. It will generate this code for you automatically.
 

Mac_Max

macrumors 6502
Mar 8, 2004
404
1
You can also create custom getters and setters if you'd like:

Code:
 @property(getter=getFoo, setter=setFoo:) NSData *foo;
 

ArtOfWarfare

macrumors G3
Nov 26, 2007
9,544
6,042
You can also create custom getters and setters if you'd like:

Code:
 @property(getter=getFoo, setter=setFoo:) NSData *foo;

Or just skip properties altogether... There's no reason you can't just use setters and getters (but there's less boilerplate code involved if you use properties.)
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.