2

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 } 
1
  • You can't really "pass" it as such, instead you make it a property or instance variable of the class, giving access to it from the other method. If the method just wants the value for that invocation only (in other words the values doesn't need to persist with the object), then that other method should accept parameters. Commented Apr 25, 2014 at 9:49

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

Comments

0

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.

2 Comments

No! That will limit the number of instances of the class to 1.
You should add a note to your answer expanding on the fact that myInt will only have one instance across the whole of the class (and subclasses).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.