NSString being set but appears empty when calling from another class - iOS - objective-c

I have a small piece of code that sets the NSString (strUsername) of the class Username to the value which is typed into a UITextField and then a button is pressed. This works fine:
UsernameViewController.m
#import <UIKit/UIKit.h>
#import "Username.h"
#interface UsernameViewController : UIViewController
{
Username *username;
__weak IBOutlet UITextField *test;
}
#property (nonatomic, retain)IBOutlet UITextField *txtUsername;
#property (nonatomic, retain) IBOutlet UITextField *test;
-(IBAction)setUsername;
#end
#import "UsernameViewController.h"
#import "Username.h"
#implementation UsernameViewController
#synthesize test=_test;
- (void)viewDidLoad
{
[super viewDidLoad];
username = [[Username alloc] init];
}
-(IBAction)setUsername
{
NSString *inputUsername = self.test.text;
NSLog(#"inputUsername is: %#", inputUsername);
username.strUsername = inputUsername;
NSLog(#"the username.strUsername is now: %#", username.strUsername);
}
My NSLog output shows that the UItextfield input and NSString setter are working:
LocNews1[6699:707] inputUsername is: Harry brown
LocNews1[6699:707] the username.strUsername is now: Harry brown
Now when it hit the back button on this view it return me back to a UITableViewController. I then perform a pull down to refresh action and its called the following method:
TestViewController.m (UITableViewController type)
#import "TestViewController.h"
#import "ViewController.h"
#import "DetailViewController.h"
#import "AppDelegate.h"
#import "NewsArticle.h"
#import "ResultsCustomCell.h"
#import "XMLParser.h"
#implementation TestViewController
//some code
- (void)addItem
{
username = [[Username alloc] init];
// Use XMLparser to check for updated new feeds.
if(username.strUsername != NULL)
{
NSLog(#"ViewController username.strUsername is:%#",username.strUsername);
activeUsername = username.strUsername;
}
else
{
NSLog(#"%#",username.strUsername);
activeUsername = #"";
}
NSString *myLat = [[NSString alloc] initWithFormat:#"%f", locationManager.location.coordinate.latitude];
NSString *mylong = [[NSString alloc] initWithFormat:#"%f", locationManager.location.coordinate.longitude];
XMLParser *parseQuestionnaire = [[XMLParser alloc] init];
NSLog(#"username %#",activeUsername);
newsArticle = [parseQuestionnaire parseXML:myLat:mylong:activeUsername];
[self.tableView reloadData];
[self stopLoading];
}
However this shows the NSLog output as:
LocNews1[6699:707] ViewController username.strUsername is:
As you can see the string has been set in UsernameViewController.m but when I try and call the string back in TestViewController.m is appears to be blank (there is no null in the NSLog, just blank);
What could be causing this?
EDIT: Username.h/m
#import <Foundation/Foundation.h>
#interface Username : NSObject
{
NSString *strUsername;
}
#property (nonatomic, retain) NSString *strUsername;
#end
#import "Username.h"
#implementation Username
#synthesize strUsername;
-(id)init
{
strUsername = [[NSString alloc] init];
return self;
}
#end
Note: Username is declared in both TestViewController.h and UsernameViewController.h like: Username *username;

The username instance variable in that instance of UsernameViewController is completely unrelated to the username instance variable in the instance of TestViewController. You'll need to store the variable in a place that both controllers know about or pass it between them if you want them both to have access. Simply having two variables with the same name doesn't connect them in any way.

Related

I have two error : No visible #interface for 'UIWebview'

I have two error :No visible #interface for 'UIWebView' declares the selector 'highlightAllOccurencesOfString:'
another one:No visible #interface for 'UIWebView' declares the selector 'removeAllHighlights'
Please someone help me.
WBSecondViewController.h
#import <UIKit/UIKit.h>
#interface WBSecondViewController : UIViewController <UIWebViewDelegate, UIScrollViewDelegate>{
}
#property (weak, nonatomic) IBOutlet UIWebView *webView;
#property(copy) NSArray *menuItems;
#property (weak, nonatomic) IBOutlet UIToolbar *webToolBar;
- (IBAction)back:(id)sender;
- (IBAction)foward:(id)sender;
-(IBAction)searchButtonPressed:(id)sender;
-(IBAction)clearHighlights:(id)sender;
#end
WBSecondViewController.m
#import "WBSecondViewController.h"
#import "Word.h"
#import "WordController.h"
#import "AddWordController.h"
#import "WBAppDelegate.h"
#import "WBFirstViewController.h"
#import "SearchWebView.h"
#interface WBSecondViewController ()
#end
#implementation WBSecondViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"Second", #"Second");
self.tabBarItem.image = [UIImage imageNamed:#"second"];
}
return self;
}
- (void)viewDidLoad
{
UIMenuController *menu = [UIMenuController sharedMenuController];
[super viewDidLoad];
NSURL *theURL = [NSURL URLWithString:#"http://www.google.co.jp"];
[_webView loadRequest:[NSURLRequest requestWithURL:theURL]];
}
-(IBAction)searchButtonPressed:(id)sender{
[_webView highlightAllOccurencesOfString:#"cat"];
}
-(IBAction)clearHighlights:(id)sender{
[_webView removeAllHighlights];
}
SearchWebView.h
#import <Foundation/Foundation.h>
#interface SearchWebView : UIWebView
- (NSInteger)highlightAllOccurencesOfString:(NSString*)str;
- (void)removeAllHighlights;
#end
SearchWebView.m
#import "SearchWebView.h"
#implementation SearchWebView
- (NSInteger)highlightAllOccurencesOfString:(NSString*)str
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"UIWebViewSearch" ofType:#"js"];
NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
[self stringByEvaluatingJavaScriptFromString:jsCode];
NSString *startSearch = [NSString stringWithFormat:#"uiWebview_HighlightAllOccurencesOfString('%#')",str];
[self stringByEvaluatingJavaScriptFromString:startSearch];
NSString *result = [self stringByEvaluatingJavaScriptFromString:#"uiWebview_SearchResultCount"];
return [result integerValue];
}
- (void)removeAllHighlights
{
[self stringByEvaluatingJavaScriptFromString:#"uiWebview_RemoveAllHighlights()"];
}
#end
U have subclassed uiwebview and called it SearchWebView but then when you create an instance of web view in your wbsecondviewcontroller, you use a regular web view instead of the subclass that you created and the regular web view does not have the two extra methods that you defined for that custom one. Above #interface in the wbsecondviewcontroller.h do #class SearchWebView. Then where you declare the property UiWebView, declare it as a SearchWebView instead. In the .m file of the wbsecondviewcontroller do #import "SearchWebView.h"

Objective-C NSMutableArray not adding object

It seems like I have a problem and don't know if I'm doing this right since I'm just starting objective c.
Right now I have two files
Stores.h
#import<Foundation/Foundation.h>
#import<MapKit/MapKit.h>
#interface Stores: NSObject
#property(nonatomic,strong) NSString *storeName;
#property(nonatomic,strong) NSMutableArray *MenuItems;
#end
Stores.m
#import "Stores.h"
#synthesize storeName,MenuItems;
#end
Menu.h
#import<Foundation/Foundation.h>
#interface Menu: NSObject
#property(nonatomic,strong) NSString *MenuItemDescription;
#property(nonatomic) int MenuItemPrice;
#end
Menu.m
#import "Menu.h"
#synthesize MenuItemDescription,MenuItemPrice;
#end
ViewController.m
#import "ViewController.h"
#import "Stores.h"
#import "Menu.h"
#interface ViewController ()
#end
#implementation ViewController
NSMutableArray *stores;
-(void) viewDidLoad
{
[super viewDidLoad];
stores = [[NSMutableArray alloc]init];
Stores *store = [[Stores alloc]init];
[store setStoreName:#"Store1"];
Menu *menuItem = [[Menu alloc]init];
[menuItem setMenuItemDescription:#"Item1"];
[menuItem setMenuItemPrice: 7]
[store.MenuItems addObject:menuItem]; //won't add menuItem to store.MenuItems
[stores addObject:store];
}
#end
So it doesn't end up adding any object to store.
If I run it in debug it says that MenuItems has zero objects.
I know I'm doing something wrong but like I said I'm new to iOS.
You did not (at least in the code you show) alloc/create/assign MenuItems, so it will still be nil. Calling addObject (or anything) on nil is just a no-op.
Try this
Stores *store = [[Stores alloc]init];
store.MenuItems = [NSMutableArray arrayWithCapacity: 10];

Why I get this error? At Xcode [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
I have two error : No visible #interface for ‘UIWebview’
Why I get this error at Xcode. Error is that:No visible #interface for 'UIWebView' declares the selector 'highlightAllOccurencesOfString:' and No visible #interface for 'UIWebView' declares the selector 'removeAllHighlights'. Where are wrong?
WBSecondViewController.h
#import <UIKit/UIKit.h>
#interface WBSecondViewController : UIViewController <UIWebViewDelegate, UIScrollViewDelegate>{}
#property (weak, nonatomic) IBOutlet UIWebView *webView;
#property (weak, nonatomic) IBOutlet UIToolbar *webToolBar;
- (IBAction)searchButtonPressed:(id)sender;
- (IBAction)clearHighlights:(id)sender;
- (NSInteger)highlightAllOccurencesOfString:(NSString*)str;
- (void)removeAllHighlights;
#end
WBSecondViewController.m
#import "WBSecondViewController.h"
#interface WBSecondViewController ()
#end
#implementation WBSecondViewController
-(IBAction)searchButtonPressed:(id)sender{
NSLog(#"highlighttes");
[_webView highlightAllOccurencesOfString:#"不明"];
}
-(IBAction)clearHighlights:(id)sender{
[_webView removeAllHighlights];
}
- (NSInteger)highlightAllOccurencesOfString:(NSString*)str
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"UIWebViewSearch" ofType:#"js"];
NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
[_webView stringByEvaluatingJavaScriptFromString:jsCode];
NSString *startSearch = [NSString stringWithFormat:#"uiWebview_HighlightAllOccurencesOfString('%#')",str];
[_webView stringByEvaluatingJavaScriptFromString:startSearch];
NSString *result = [_webView stringByEvaluatingJavaScriptFromString:#"uiWebview_SearchResultCount"];
return [result integerValue];
}
- (void)removeAllHighlights
{
[_webView stringByEvaluatingJavaScriptFromString:#"uiWebview_RemoveAllHighlights()"];
}
#end
These two lines are wrong,
[_webView highlightAllOccurencesOfString:#"不明"];
[_webView removeAllHighlights];
It should be,
[self highlightAllOccurencesOfString:#"不明"];
[self removeAllHighlights];
You are trying to call highlightAllOccurencesOfString and removeAllHighlights which are defined in WBSecondViewController's #interface but on UIWebview objects. Compiler is not able to find it in UIWebView class #interface and hence the error message as No visible #interface for 'UIWebView' declares the selector ...
highlightAllOccurencesOfString and removeAllHighlights are method defined in your WBSecondViewController, while you are attempting to call them on a UIWebView object. Try with this:
-(IBAction)searchButtonPressed:(id)sender{
NSLog(#"highlighttes");
[self highlightAllOccurencesOfString:#"不明"];
}
-(IBAction)clearHighlights:(id)sender{
[self removeAllHighlights];
}
This will at least compile.

random generator to obtain data from array not displaying

I know theres a better solution using arc4random (it's on my to-try-out-function list), but I wanted to try out using the rand() and stand(time(NULL)) function first. I've created a NSMutableArray and chuck it with 5 data. Testing out how many number it has was fine. But when I tried to use the button function to load the object it return me with object <sampleData: 0x9a2f0e0>
- (IBAction)generateNumber:(id)sender {
srand(time(NULL));
NSInteger number =rand()% ds.count ;
label.text = [NSString stringWithFormat:#"object %#", [ds objectAtIndex:number] ];
NSLog(#"%#",label.text);
}
While I feel the main cause is the method itself, I've paste the rest of the code below just incase i made any error somewhere.
ViewController.h
#import <UIKit/UIKit.h>
#import "sampleData.h"
#import "sampleDataDAO.h"
#interface ViewController : UIViewController
#property (weak, nonatomic) IBOutlet UILabel *label;
#property (weak, nonatomic) IBOutlet UIButton *onHitMePressed;
- (IBAction)generateNumber:(id)sender;
#property(nonatomic, strong) sampleDataDAO *daoDS;
#property(nonatomic, strong) NSMutableArray *ds;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize label;
#synthesize onHitMePressed;
#synthesize daoDS,ds;
- (void)viewDidLoad
{
[super viewDidLoad];
daoDS = [[sampleDataDAO alloc] init];
self.ds = daoDS.PopulateDataSource;
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[self setLabel:nil];
[self setOnHitMePressed:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (IBAction)generateNumber:(id)sender {
srand(time(NULL));
NSInteger number =rand()% ds.count ;
label.text = [NSString stringWithFormat:#"object %#", [ds objectAtIndex:number] ];
NSLog(#"%#",label.text);
}
#end
sampleData.h
#import <Foundation/Foundation.h>
#interface sampleData : NSObject
#property (strong,nonatomic) NSString * object;
#end
sampleData.m
#import "sampleData.h"
#implementation sampleData
#synthesize object;
#end
sampleDataDAO.h
#import <Foundation/Foundation.h>
#import "sampleData.h"
#interface sampleDataDAO : NSObject
#property(strong,nonatomic)NSMutableArray*someDataArray;
-(NSMutableArray *)PopulateDataSource;
#end
sampleDataDAO.m
#import "sampleDataDAO.h"
#implementation sampleDataDAO
#synthesize someDataArray;
-(NSMutableArray *)PopulateDataSource
{
someDataArray = [[NSMutableArray alloc]init];
sampleData * myData = [[sampleData alloc]init];
myData.object= #"object 1";
[someDataArray addObject:myData];
myData=nil;
myData = [[sampleData alloc] init];
myData.object= #"object 2";
[someDataArray addObject:myData];
myData=nil;
myData = [[sampleData alloc] init];
myData.object= #"object 3";
[someDataArray addObject:myData];
myData=nil;
myData = [[sampleData alloc] init];
myData.object= #"object 4";
[someDataArray addObject:myData];
myData=nil;
myData = [[sampleData alloc] init];
myData.object= #"object 5";
[someDataArray addObject:myData];
myData=nil;
return someDataArray;
}
#end
what i guess is going on is that nslog function cant print the data inside your sample data class because its not a standard class. not standard classes must implement the "description" method. What you get when you print out your class is the pointer to it, because nslog has no way of knowing how to print out the data in your class.
if what you want to print on that label/nslog is the nsstring inside your class "sampledata" you should access the property.
this can be done in the following way:
SampleData *instanceOfSampleData = (SampleData*)[ds objectAtIndex:number];
label.text = [NSString stringWithFormat:#"object %#", instanceOfSampleData.object];

I'm having problems using a Singleton to pass an array in Objective-c. (code included)

So I'm creating an array called fruits which I would like to share between multiple views. This is my code:
#import <foundation/Foundation.h>
#interface MyManager : NSObject {
NSMutableArray *fruits;
}
#property (nonatomic, retain) NSMutableArray *fruits;
+ (id)sharedManager;
#end
#import "MyManager.h"
static MyManager *sharedMyManager = nil;
#implementation MyManager
#synthesize fruits;
#pragma mark Singleton Methods
+ (id)sharedManager {
#synchronized(self) {
if (sharedMyManager == nil)
sharedMyManager = [[self alloc] init];
}
return sharedMyManager;
}
- (id)init {
if ((self = [super init])) {
fruits = [[NSMutableArray alloc] init];
}
return self;
}
-(void) dealloc{
self.fruits = nil;
[super dealloc];
}
#end
Now I'm using the following code so that I can use workouts in the new view
#import "MyManager.h"
#interface Chest : UIViewController {
IBOutlet MyManager *fruits;
}
#property (nonatomic, retain) IBOutlet MyManager *fruits;
-(IBAction) goToList: (id) sender;
#end
When a button is clicked, goToList is called, and I populate my array, fruits
#import "Chest.h"
#implementation Chest
#synthesize fruits;
-(IBAction) goToList:(id)sender{
MyManager *fruits = [MyManager sharedManager];
NSString *filePath;
NSString *fileContents;
filePath = [[NSBundle mainBundle] pathForResource:#"chest_strength" ofType:#"csv"];
fileContents = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
fruits = [fileContents componentsSeparatedByString:#"\n"];
}
When I output the elements of *fruits in this view, everything works fine. Now when I try to access this same variable in the other view, it says the array is null. Here's the code for the second view:
#interface List : UIViewController {
IBOutlet MyManager *fruits;
}
#property (nonatomic, retain) IBOutlet MyManager *fruits;
#end
#import "List.h"
#import "MyManager.h"
#implementation List
#synthesize fruits
NSLog(#"%#", fruits); //This is the part that isn't displaying correctly. I'm getting a null here
So my question is, how do I do this so that I can get the array fruits that I populated in Chest and use it in List so that I can display the contents of the array in that view?
Thank you to everybody who answers. This problem is seriously bogging me down and I need to finish this project ASAP. Much appreciated.
You've changed a few things in this question but the fundamental problem remains: the array is a property of your singleton, and you are not treating it as such.
Whenever you refer to the array, outside of the singleton, do it like this:
[MyManager sharedManager].fruits
If you are accessing it frequently, you can create a local ivar, but you certainly wouldn't have it as an IBOutlet, which you are doing in your last code sample. How is that ever going to be set?