Objective-C / Java Question

Discussion in 'Mac Programming' started by Mvkoe, Dec 7, 2012.

  1. macrumors member

    Mvkoe

    Joined:
    Aug 4, 2008
    Location:
    Belgium
    #1
    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(){
    	
    	}
    }
    
     
  2. macrumors 6502a

    Joined:
    Jan 23, 2010
    Location:
    San Diego, CA USA
    #2
    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];
    
    Use @property. It will generate this code for you automatically.
     
  3. macrumors 6502

    Joined:
    Mar 8, 2004
    #3
    You can also create custom getters and setters if you'd like:

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

    ArtOfWarfare

    Joined:
    Nov 26, 2007
    #4
    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.)
     

Share This Page