I have an array called client in one of my classes and I want to use the information in that array in another class that i have. I have set up the property and synthesized the array in my first class. The code for my first class is
#synthesize client;
...
- (IBAction)testing:(id)sender {
NSString *textContent = myTextView.text;
textContent = [textContent stringByReplacingOccurrencesOfString:#" " withString:#""];
client = [textContent componentsSeparatedByString:#"."];
NSLog(#"%#", client);
}
In my second class I tried importing the h file for my first class and then just accessing the array. The code that I am using is
- (IBAction)ButtonStuff:(id)sender {
ArrayManipulationViewController *myClass = [[ArrayManipulationViewController alloc]init];
NSLog(#"Second Interface");
NSArray *test = myClass.client;
NSLog(#"%#", test);
}
To access object from multiple classes, a common approach is to declare the object in the parent class, and then pass a shared instance of that object to all child classes that require access. For instance, you could declare the array in the AppDelegate, and set array properties in your subclasses, and pass the instance of the array from the AppDelegate to all your subclasses.
Eg: create an NSArray (myArray) in your app delegate, then in the AppDelegate implantation, pass the myArray instance to your sub view controllers using properties.
Or, if you'd prefer; you can declare the array in your first class, and then pass the array instance from your first class to your second class using properties. Then, any changes made in your second class will be available in your first class, since the INSTANCE is the same.
UPDATED ANSWER:
For the second approach, you're best declaring the array in your first class implementation, and then when you instantiate the second class, pass the instance of the array to the second class using properties. In this example, you'll need to have an NSArray property in your second class to be able to pass the array over to it using [secondClassInstance setClient: client];
Your second class interface might look like this:
#interface SecondClass : NSObject
{
NSArray *client;
}
#property (nonatomic, retain) NSArray *client; // don't forget to synthesize
#end
Then, in your first class, you can do the following to pass over your instance of the array:
NSArray *client = [[NSArray alloc] initWithObjects:#"Object 1", #"Object 2"];
//...
SecondClass *secondClass = [[SecondClass alloc] init];
[secondClass setClient: client]; // passing the original client instance here
// don't forget to release secondClass instance when finished
Related
I'm using this following code pass data to my third controller:
[self presentControllerWithName:#"ThirdView" context:MyArray];
The thing is, I would like to pass more than a simple array. I would like to pass a separate string, and another array if possible, and I don't want to add the string or the other array to "MyArray".
Is there a different way of going about this, or do I just restructure this code?
You can create custom object with the data you want to pass or you can bundle the data in the dictionary or array. In swift you can use tuple as well.
This is an example with dictionary:
NSDictionary *myData = #{
#"MainArray" : MyArray,
#"MyString" : #"string",
#"AnotherArray" : anotherArray
};
[self presentControllerWithName:#"ThirdView" context: myData];
Example with Array:
NSArray *myData = #[MyArray, #"string", anotherArray];
[self presentControllerWithName:#"ThirdView" context: myData];
While you could use a dictionary or an array as Greg has suggested, you get no type-safety and you have to ensure that the key names / indexes are the same in both places.
A better approach would be to subclass NSObject and provide a wrapper for the data you are wanting to transfer to that view controller.
Interface:
#interface ThirdViewState : NSObject
#property (nonatomic, copy) NSString *title;
#property (nonatomic, copy) NSArray *list;
#end
Simple empty implementation:
#implementation ThirdViewState
#end
Then you can construct an instance of this object, populate it with data and pass it to the view controller:
ThirdViewState *state = [[ThirdViewState alloc] init];
state.title = #"My 3rd view";
state.list = myArray;
[self presentControllerWithName:#"ThirdView" context:state];
Then in the third view controller's awakeWithContext: method you can pull out the data:
- (void)awakeWithContext:(ThirdViewState *)state {
[super awakeWithContext:state];
// do whatever with state
}
I have created a custom class of NSObject, and I would like to access some instance variables from my main View Controller to that custom class, how do you do that?
EDIT: Perhaps I was unclear in my first formulation. It is the instance variables from the ViewController class I would like to access, not the ivars from my custom class.
If I got you right, the simplest way is to pass view controller instance during initialization. Just implement initWithViewController:(UIViewController*)vc in your custom class.
You should expose your data as properties in your NSObject subclass. You can find a description of properties at this tutorial: http://rypress.com/tutorials/objective-c/properties.html.
You should better use properties to easy access to some info in your custom class.
They automatically generate iVars.
Also you can access public (declared in .h file) ivars directly:
#interface CustomClass : NSObject
{
NSArray *_array1;
}
#property (nonatomic, strong) NSArray *array2;
CustomClass *instance = [CustomClass new];
NSArray *a1 = instance->_array1;
NSArray *a2 = instance.array2;
Can we initalize dynamically any Modal class. rather than creating any NSObject class with property values as likes string inside that class.
default we do code as like:
in .h file
#interface MyUser : NSObject
#property (nonatomic, strong) NSString *username,*bio,*website;
#end
in .m file
#implementation InstaUser
#synthesize bio;
#end
To use that we do:
MyUser *sendUser = [[MyUser alloc]init];
sendUser.username = #"JHON";
sendUser.bio = #"abcdcskdfhksfjhfkjsdf";
I Don't want to create so many this type of modal class rather then this just any dynamic method to initalize class property and use it by inline code.
You can use run time feature of objective c class.
Create a single model class and add property to it dynamically at run time:
For more reference :
How can I add properties to an object at runtime?
I think you meant a flexible model object with dynamically declared properties something like this:
MyModel *user = [[MyModel alloc] init];
user.name = #"name";
MyModel *something = [[MyModel alloc] init];
something.dynamicProperty = #"blahblah";
If so, you cannot. Use NSMutableDictionary instead, or consider to generate model classes from a simple config file by some scripts.
I have two classes each with an instance method that use the same piece of code.
This piece of code takes a NSString and return an NSArray.
Currently the same piece of code is repeated in the two classes.
Is there a way to write it separately and call it by the two classes? I tried to make a method in a subclass of NSArray, but there are many problems due to the fact that NSArray is an abstract class. Any suggestions?
Thank you.
Instead of subclassing NSArray, the correct approach to extent the behaviour of a class is to create a category on that class.
So, you can create a category on NSString that returns an array, and after you have imported that category to your project, you can call it as if it was part of NSString, for example:
NSString *myString = #"Hello";
NSArray *myArray = [myString generateArrayFromString];
You can find a guide on how to create a category here:
Customizing Existing Classes
You can try to make a NSString category. This category will return the array.
E.g.:
//
// NSString+MyCategory.h
#import
#interface NSString (MyCategory)
-(NSArray *)myMethod;
#end
//
// NSString+MyCategory.m
#import "NSString+MyCategory.h"
#implementation NSString (MyCategory)
-(NSArray *)myMethod {
NSArray *_arr = [self componentsSeparatedByString:#","];
return _arr;
}
#end
Then in your class (or whatever you want in your code) you can import the category:
#import "NSString+MyCategory.h"
and then use it on any string:
NSArray *myArray = [anyString myMethod];
From the sound of it (parsing a string into an NSArray, with on reference to the class's instance fields) you can make the method a class (vs instance) method and invoke it from either class.
Ie:
+(NSArray*)parseThisString:(NSString*)theString {
doSomething;
return result;
}
Invoke with [TheNameOfTheClass parseThisString:inputString].
Of course, if you are reverencing values in the class's instance this won't work.
I've tried several ways that i've found here but none have worked. what would be an easy way to pass this NSMutalbeArray into another View controller?
NSMutableArray *pph = [[NSMutableArray alloc] init];
[pph addObject:[NSString stringWithFormat:#"%d %d %d",diario.Cowid,diario.Lact,diario.Del]];
on the same file below i have
- (IBAction)masInfoPPH;
{
tipo = #"PPH";
adiario = pph;
NSLog(#"\n Array adiario: %#",pph);
DetDiarioViewController *DetDiarios = [[DetDiarioViewController alloc] initWithNibName:nil bundle:nil];
[self.navigationController pushViewController:DetDiarios animated:YES];
}
for some reason pph (the NSMutalbeArray) gets here as null but up there it does give me the objects it should have. adiario is a global array or at least its supposed to be. Help!
There really are no global arrays. Create a property in your class for pph in the interface of your class.
#property(nonatomic, strong) NSMutableArray *pph;
self.pph = [[NSMutableArray alloc] init];
[self.pph addObject:[NSString stringWithFormat:#"%d %d %d",diario.Cowid,diario.Lact,diario.Del]]
But you still need to get that into next view controller. Create a similar property in it's interface and then set it before pushing
DetDiarioViewController *detDiarios = [[DetDiarioViewController alloc] initWithNibName:nil bundle:nil];
detDiarios.pph = self.pph;
[self.navigationController pushViewController:detDiarios animated:YES];
BTW - in objective-c the convention is to use a lowercase letter for the first letter of an instance
The scope of your pph array is unclear from your description.. But ANYTHING declared inside a single method is LOCAL to that method, unless it is returned BY that method.
You have several options... Declare the array as an instance variable, ie..
#interface YourClass: NSObject { NSMutableArray *pph; }
or
#implementation YourClass { NSMutableArray *pph; }
or as a static variable (in your .m file) (which would enable you to access the value from Class (+) methods..
static NSMutableArray *pph = nil;
or most preferably... as a property
#interface YourClass #property (strong) NSMutableArray *pph;
which you can then call upon from any instance method via the automatically synthesized Ivar _pph, or via the property's accessors.. self.pph.
Hope this helps!