Using an object in different methods in Objective C

0

I'm trying to work with objects in iOS Objective C, and I had a question regarding usage.

I created a file called carro.h

#import <Foundation/Foundation.h>
@interface carro : NSObject
{
    NSString *_marca;
    NSString *_ano;  
}
@property (strong) NSString *marca;
@property (strong) NSString *ano;
@end

In the file carro.m I have the following

#import "carro.h"
@implementation busca
@synthesize marca;
@synthesize ano;
@end

I have a ViewController and I want to use this object by assigning value or rescuing the value. But how to make the same object be used in different methods?

    
asked by anonymous 29.05.2014 / 02:04

1 answer

5

First, by convention, class names in Objective C have the first capital letter. In most cases, it is not necessary to synthesize ownership. The compiler will automatically generate the instance variable. Ex: When declaring @property (strong) NSString *marca; the compiler will automatically generate the instance variable _marca . The instance variable is only accessible in the class implementation. Access to the property depends on the modifiers in the declaration: readonly, readwrite (default). Here is an example:

Car.h

@interface Carro : NSObject

@property (copy, nonatomic) NSString *marca;
@property (copy, nonatomic) NSString *modelo;
@property (assign, nonatomic) NSUInteger ano;
@end

Car.m

@implementation Carro
- (instancetype)init {
    self = [super init];
    if (self) {
        _marca = @"VW";
        _modelo = @"Fusca";
        _ano = 1979;
    }
    return self;
}
@end

ViewController.m

//Exemplo de utilização da classe Carro
@implementation ViewController {
    Carro *carro;
}

- (void)methodA {
    carro = [Carro new];
    NSLog(@"%@ %d", carro.modelo, carro.ano);//Fusca 1979
    [self methodB];
}

- (void)methodB {
    [carro setAno:2014];
    [carro setModelo:@"Gol"];
    NSLog(@"%@ %d", carro.modelo, carro.ano);//Gol 2014
}

If you are in doubt as to the concepts of object orientation and MVC I suggest you study these topics before deepening your studies in Objective C.

    
29.05.2014 / 03:16