stereojump
stereojump

Reputation: 21

How to pass variable value to a method without parametrs in objective-c?

I'm I newbie to objective-c & C lang and maybe I miss some basic principles. But how can I pass a variable value from one method without parameters to another inside one class?

- (id)init
{
    self = [super init];
    if (self) {
        myInt = 1;
    }
    return self;
}
-(void)methodOne
{
    myInt = 5;
}
-(void)methodTwo
{
    NSLog(@"%i", myInt); // 1
}

Upvotes: 2

Views: 80

Answers (4)

Popeye
Popeye

Reputation: 12093

You want to use a property so try this

MyClass.h

@interface MyClass : NSObject

// Because the property is here it is public so instances
// of this class can also access it.
@property (assign) int myInt;    

@end

MyClass.m

#import "MyClass.h"

// If you wish to make the property private then remove the property from above and add
// Only do this if you want it to be private to the implementation and not public
@interface MyClass()
@property (assign) int myInt; 
@end

@implementation MyClass

// The synthesize is done automatically so no need to do it yourself

- (id)init
{
    self = [super init];
    if(self) {
        // Set the initial value of myInt to 1
        self.myInt = 1;
    }
    return self;
}

- (void)methodOne
{
    // Reassign to 5
    [self setMyInt:5];
}

- (void)methodTwo
{
     // NSLog the value of the myInt
     NSLog(@"MyInt is equal to: %d", [self myInt]);
}
@end

There is quite a bit of Apple documentation on properties in objective-c, so here they are:

Naming Properties and Data Types

Encapsulating Data

Declared property

Defining Classes

Enjoy a good read.

Upvotes: 1

Watsche
Watsche

Reputation: 438

global variable after @implementation:

@implementaion blabla

int myInt = 10;

But at this way the number of your instance will be limited by 1. If you need only one instance, you can use it that way.

Upvotes: 0

Rich Pickering
Rich Pickering

Reputation: 237

You would make myInt a member of the class which the methods are a part of in order to achieve what I think you're trying to achieve...

Declaring private member variables

Upvotes: 0

soprof
soprof

Reputation: 326

You probably want to have a property inside your class.

Simply talking, property is a variable for instances of your class. More info: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/DefiningClasses/DefiningClasses.html#//apple_ref/doc/uid/TP40011210-CH3-SW7

Upvotes: 2

Related Questions