using string variable from one class in another - iphone

Rookie question: I am writing a program that will generate a specific string and then display it in a text window in a different view controller. I have been testing to ensure that the code in fact generates the string using NSLog commands and I know the code is working as intended. For some reason it is not transferring across the view controller and I cant figure out why. Any help? Here is a snippet of the code:
CreateStoryViewController.m
- (IBAction)makeStory:(id)sender
{
StoryLine *myStory =[[StoryLine alloc] init];
[myStory setStory];
self.story = myStory.plot;
NSLog(#"story is %#", self.story);//this is generating the correct story string
self.displayStoryController = [[BIDDisplayStoryViewController alloc] initWithNibName:#"DisplayStoryView" bundle:nil];
[self.view insertSubview:self.displayStoryController.view atIndex:1];
}
DisplayStoryViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
BIDCreateStoryViewController *newStory = [[BIDCreateStoryViewController alloc] init];
NSLog(#"newStory.story is %#",newStory.story);//this generates null message
self.storyDisplay.text = newStory.story;
}

This is wrong. You're instantiating a new BIDCreateViewController object inside your second view controller. This is not the same as the original BIDCreateViewController object that pushed your second BIDDisplayStoryViewController.
You need to declare a string property in your BIDDisplayStoryViewController's header file.
Something like
#property (nonatomic, retain /*or strong, if using ARC*/) NSString *storyToDisplay;
Be sure to synthesize this in your implementation file as well.
When you create BIDDisplayStoryViewController inside your first view controller, you need to do it as follows:
self.displayStoryController = [[BIDDisplayStoryViewController alloc] initWithNibName:#"DisplayStoryView" bundle:nil];
self.displayStoryViewController.storyToDisplay = self.story;
Now inside your second view controller you can access this using self.myStory.
While this will solve your problem (and please do understand that it's not my intention to be rude here), I feel that there's a lack of understanding of how iOS (and OOP in general) works.

In your viewDidLoad method you are making a whole new story. This story is totally different from the one you made in the makeStory: method. You should add a StoryLine Property to DisplayStoryViewController.h, and set that after you init your displayStoryController.

make the intended variable a property type at .h file, so the other file can access it

Related

Passing Image through UINavigationController

I have an image in my RootViewController (which is selected from a UIImagePickerController), which I need to pass to a new view through a navigation controller. I have the following code that I use to pass strings to the next view:
//Get strings
NSString *text1 = line1.text;
NSString *text2 = line2.text;
NSString *text3 = line3.text;
NSString *text4 = line4.text;
//Create an GeneratedViewController and initialise it with given data
GeneratedViewController *gController = [[GeneratedViewController alloc] initWithNibName:#"GeneratedViewController" bundle:[NSBundle mainBundle]];
gController.text1 = text1;
gController.text2 = text2;
gController.text3 = text3;
gController.text4 = text4;
[self.navigationController pushViewController:gController animated:YES];
[gController release];
gController = nil;
How might I pass an image to the GeneratedViewController?
Thanks,
Jack
The easiest solution would be to create a property of type UIImage on GeneratedViewController.
Then after creating and initializing the GeneratedViewController but before pushing it onto the navigationController you will need to set the image property on the gController to the selected image.
A property on the controller, just like the text is set
In a method, or the initializer
through a notification (NSNotificationCenter). This is a bit more advanced.
Through delegation, where the first controller is a datasource delegate on the Generated Controller. This allows the second controller to get what it needs, whenever it wants.
Which method to use depends on how the controllers are created, when the image can change, and how many different pieces of data the second controller needs - one or two bits, properties work fine. More than that, I tend to use delegation.

updating value of modal view variable

I'm trying to make a modal view which displays the champion of my app.
there's a NSMutableString variable called champ in modal view,
which is supposed to be updated by returnChamp function in main view.
the champ string is correctly set in main view,
but in modal view, the champ value appears as (null).
In fact, it seems it doesn't even go into the returnChamp function.
so apparently something wrong with my calling or implementing returnChamp,
but I have another function that does the similar, and that works fine.
could anyone please help me?
-(void) mainView{
.....
champ = [[currentPlayers objectAtIndex:playerIndex] retain];
NSLog(#"%#",champ);
modalWinner = [[winner alloc] init];
modalWinner.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentModalViewController:modalWinner animated:YES];
}
- (NSMutableString *) returnChamp{
NSLog(#"returnChamp");
return champ;
}
//in modalWinner
-(void) modalView{
..............
champName = [[NSMutableString alloc] init];
NSLog(#"%#", [(MainViewController *)self.parentViewController returnChamp]);
champName = [(MainViewController *)self.parentViewController returnChamp];
UIImage *champImage = [UIImage imageNamed:champName];
}
self.parentViewController is probably not actually a reference to your object. For some reason, it seems that the framework always insists on setting a UINavigationController as self.parentViewController - even for modals, and to the extent that it will create one if there isn't already one. This is probably going unnoticed because you're casting it to your MainViewController type.
You'll need to find a different way of making your original object available to be communicated with, or perhaps pass the appropriate value to the newly-instantiated controller before you present it.
For example, if you add a champName property to the modal class, you can do:
modalWinner = [[ModalWinnerViewController alloc] init];
modalWinner.champName = myValue; /* Set value before presenting controller */
[self presentModalViewController:modalWinner animated:YES];
There will probably be some code needed to update the UI with this value. The viewWillAppear method of the modal view controller is a good place for this as it is called by the framework immediately before the view is presented.
Note that this property-based approach could be used to keep a reference to your intended parent object, as well. And see here for a different approach to solving a similar problem.

objective-c delegates and events design (I don't get it)

I'm pretty new to the objective-c language (less than three months) but it is something that i really need to understand.
Suppose there is a controller (in a iOS environment) that manages a table view for input data from the user. The table must have editable cells and some features to make the value selection easier, for example a button that shows a popover with the possible values for a field.
Suppose there is a field to store country names. The popover first shows a list of continents; when the user selects a continent, the controller of the popover must show the countries of the previews selected continent.
Now, this popover appears in many places in the app so it will be nice if I can encapsulate it for later use. What i will expect for this popover is something like this:
...
#protocol MyPopoverDelegate<NSObject> {
-(void)didSelectCountry:(NSString *)countryName;
{
...
MyPopoverController *dataSelector = [[MyPopoverController] alloc] init];
dataSelector.dataType = CountryDataType;
dataSelector.delegate = self;
[dataSelector show];
[dataSelector release];
...
The problem here is the line [dataSelector release] because the code for managing the popover must stay alive until the country is selected. That's means the dataSelector variable must be a property of the caller class and that sucks.
The question then is:
How can i organize situations like this to have a reusable controller?
Thanks
Edited after vodkhang answer:
Ok, that's a good one, but dataSelector still is a property.
What if i do:
#implementation MyPopoverController
- (id)init {
...
[self retain];
...
}
- (void)popoverControllerDidDismissPopover: (UIPopoverController *)popoverController {
...
[delegate didFinishSelectingCountry:countryName];
[self release];
}
#end
I never see this behavior in objective-c, i feel that this is not the idea.
Why is it wrong?.
One of the way you can do for delegate method is to have:
MyPopOverDelegate
- (void)didFinishSelectingCountry:(NSString *)countryName popOver:(MyPopOver *)popOver;
Caller.m
// the caller
- (void)viewDidLoad {
MyPopoverController *dataSelector = [[MyPopoverController] alloc] init];
dataSelector.dataType = CountryDataType;
dataSelector.delegate = self;
[dataSelector show];
}
- (void)didFinishSelectingCountry:(NSString *)countryName popOver:(MyPopOver *)popOver {
// finish stuff
[popOver release];
}
This way is used a lot like NSUrlConnection, UIImagePickerController
If you want some unique object reusable across an entire app from anywhere in the view hierarchy, you can make it a property of the app delegate, and let the app delegate own it (retain it when live, release it during memory warnings, etc.).
A self retained object may eventually run into problems if you ever port your code to a garbage collected environment.

iPhone SDK NSInternalInconsistencyException

I'm hitting a wall over and over again, trying to solve a problem I've got in xcode. I'm a newbie and started coding just a while ago.
I'm trying to make a XML parser based on this tutorial: http://cocoadevblog.com/iphone-tutorial-creating-a-rss-feed-reader
which works fine separately, but when I'm implementing it into my own project, I get the 'NSInternalInconsistencyException' error, as a result of the following code:
----File: Parser.m----
- (void)parserDidEndDocument:(NSXMLParser *)parser {
if ([_delegate respondsToSelector:#selector(parsedInformation::)]){
[_delegate parsedInformation:information];
}else{
[NSException raise:NSInternalInconsistencyException
format:#"Delegate (%d) doesn't respond to parsedInformation:", _delegate];
}
}
I've tried to remove the if-phrase, and then it calls the correct function, but the data which is supposed to be overhanded, won't get through.
Project setup
The project is a tab-based application. I'm having three classes:
Parser
AlphaTab
RootDelegate
In RootDelegate I used the following code to initialize the tab-view, and then to initialiaze the AlphaTab as a tableView being part of a navigationView:
----RootDelegate.m ----
tabBarController = [[UITabBarController alloc] init];
alphaTab = [[AlphaTab alloc] initWithTabTitle:#"AlphaTab" navigationTitle:#"Exploring"];
UINavigationController *tableNavController = [[[UINavigationController alloc] initWithRootViewController:alphaTab] autorelease];
tableNavController.delegate = self;
[alphaTab release]; // creates your table view's navigation controller, then adds the created view controller. Note I then let go of the view controller as the navigation controller now holds onto it for me. This saves memory.
So good so far.. the problem comes when I use the Parser class, which parses a given XML file. This class is initialized and only implemented in the AlphaTab - therefore it has nothing to do with the RootDelegate class at all. The initialization is done as:
----File AlphaTab.m ----
- (void)loadData{
if(information==nil){
Parser *XMLParser = [[Parser alloc] init];
[XMLParser parseFeed:#"http://frederikbrinck.com/bodil/Example.xml" withDelegate:self];
[XMLParser release];
}else {
[self.tableView reloadData];
}
}
I'm suspecting the parameter withDelegate's value "self" to be the problem, which I think referres to the super class RootDelegate, but I'm not sure. Likewise, I don't know to pass the AlphaTab class' delegate to the function, which I think would solve the problem.
I'm ought to think, that the problem could be created from this line aswell:
----FILE: Parser.h ----
#protocol AlphaTab <UITableViewDelegate>
- (void)parsedInformation:(NSArray *)i;
#end
I've done some research about protocols and respondsToSelector, but honestly, I didn't understand much, since my code is seen from the programmatic perspective of view, without using the InterfaceBuilder at all, since I've been adviced to do that. It hasn't lead to the solution of the problem either.
For further understanding, I then want this function in AlphaTab.m to be called, when the information is parsed.
----FILE AlphaTab.m ----
- (void)parsedInformation:(NSArray *)i {
NSLog(#"The parser has completed parsing");
information = i;
NSLog(#"This is the information: %d", [[information objectAtIndex:0] objectForKey:#"tabTitle"]);
[self.tableView reloadData];
}
I've looked on the net, and I found some explications about the NSInternalInconsistencyException. I've tried to do them as well, for example by setting everybody with themselves as delegates. However, I had no luck. What wonders me most, is that when I use the Parser without having to subclass it's caller (this case: AlphaTab) to a main class, it works like a charm.
I hope you guys can give me a clue. If you need any more information please ask, and I'll be in disposition.
//Brinck10
Please see #warrenm and his comment.

initializing UIView subclass with parameters in iphone sdk?

Iam a newbiew to iPhone development. Version of my SDK is 2.2
In my code, UIViewController is used to change view dynamically once the app is launched, a method in the UIViewController is called to know which view should be initialized along with parameters, which goes to a 'switch-case' and assign a view to current view according to the parameter, like this:
case 1:
currentView = [[View01 alloc] init];
break;
case 2:
currentView = [[View02 alloc] init];
break;
and outside the switch-case:
[self.view addSubview:currentView.view];
I wonder f can pass a parameter along with initialization, like iniWithNibName or so? I need this because have to manipulate in the leaded view, according to the view from which its called.
Thanks.
One way to approach this is to modify your View01 and View02 classes to include an initWithParam: initialiser.
i.e. add
- (id) initWithParam:(NSString *)myParam;
to the #interface section and add
- (id) initWithParam:(NSString *)myParam {
if (self = [self init]) {
// handle or store 'myParam' somewhere for use later
}
return self;
}
to the #implementation section. Notice how the initWithParam: message internally calls the existing init. Obviously you could change the type, or number of parameters passed in as required.
Another approach would be to provide a property on your view class, so you could do something like the following:
currentView = [[View01 alloc] init];
currentView.myParam = #"SomeValue";
Which approach works the best will depend somewhat on your particular application needs.