Using an object in different methods in Objective C

Asked

Viewed 468 times

0

I’m trying to work with objects in iOS Objective C, and I had a question about using.

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 archive 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 assigning value or redeeming value. But how to make the same object can be used in different methods?

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 the property. The compiler will automatically generate the instance variable. Ex: when declaring @property (strong) NSString *marca; 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). Follow 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 about the concepts of object orientation and MVC I suggest you study these topics before deepening the studies in Objective C.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.