Tutorial :How can I access variables belonging to one class from an outside class?



Question:

I am new to objective c and I guess it has to do with me not understanding pointers or something, but I cannot access a variable outside the class it was declared in.

I know this is a ridiculous question, but I need help.

I have something as simple as an NSString which depending on which tablecell row is selected it grabs the name and stores it in the string. The thing is , I need this string available in another class where the file needs to be loaded using String value. I just get a string is nul or nil whatever error.

I have tried property, synthesize, imports, @class but I guess I dont know what the true meaning of those things are.

Please point me in the right direction.


In libraryTableViewController I declare

NSString *fileToLoad;  @property (nonatomic, retain) NSString *fileToLoad;   

in the .m I @synthesize fileToLoad; then in the didSelectRowAtIndexPath method I fileToLoad = @"%@", [categories objectAtIndex:row];

The problem is in another view controller class I want to load from tableViewData plist

NSString *myFile = [[NSBundle mainBundle] pathForResource:fileToLoad ofType:@"plist"];  

but just get nil; ?


Solution:1

If the code is in another class or instance, you don't have magical access to similarly named properties of other classes/instances - the documentation on declared properties might help clear misunderstandings.
In your second instance, fileToLoad is probably nil because it was never initialized there.

You need to have a reference to the instance you want to have the value from and retrieve the property value:

NSString *myFileToLoad = myTableViewController.fileToLoad;  

Depending on your architecture there might also be other/better solutions.


Solution:2

From the sounds of it, you need to read up on Object Oriented Programming. Apple have some guides on OOP and how it is implemented in Objective-C here:

http://developer.apple.com/iphone/library/documentation/cocoa/conceptual/oop_objc/articles/oooop.html


Solution:3

Just a couple of points about your code:

  1. You've declared an NSString variable to a property using retain for memory management. The correct memory management model for class clusters that have mutable/immutable types is copy
  2. Even though you've declared fileToLoad as a property, you're setting it directly in the didSelectRowAtIndex method, which bypasses the memory management and any KVO/KVC notifications that changing the property may generate. You should change the property value using self.fileToLoad except in initialisation or tear down methods.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »