I’m trying to make an app in xcode. I have made a class called myApp.m and .h
In my .m I have these lines of code
- (void)loadApp
AlarmItem *item1 = [[[AlarmItem alloc] initWithTitle:#"TEST2"] autorelease];
NSMutableArray *items = [NSMutableArray arrayWithObjects:item1, nil];
RootViewController *rootController = (RootViewController *) [navigationController.viewControllers objectAtIndex:0];
rootController.items = items;
and in my RootViewController I have an this method:
- (IBAction)RefreshMyApp:(id)sender {
MyApp *myApp2 = [[[MyAppalloc] init] autorelease];
[myApp2 loadData];
}
What I’m trying to do is calling the method from the myApp class and displayed in the tableView, but I always get an empty cell.
Any help is appreciated.
Is this meant to get you your UIApplication singleton? (i'm guessing MyAppalloc is a typo and should be MyApp alloc)
MyApp *myApp2 = [[[MyApp alloc] init] autorelease];
if so then you should be doing it like this:
MyApp *myApp2 = (MyApp*)[UIApplication sharedApplication];
If this is not the case you need to make it clearer what MyApp is (your app delegate?)
I guess, your application running in singleton instance, if this is something kind of NSView or a particular control you want to refresh, you could call its particular refresh method like,
[NSTableView reload];
[NSTextField setString];
etc...
Related
I am very new to objective c and OpenEars so please forgive me if I have some messy code and if I am lost in very simple problem.
Anyhow, I have two controllers in this application. The first being the default ViewController and the second one being a new one that I made called ReplyManagerController.
The code in the ViewController basically uses the one in the tutorial with some (maybe more some) changes.
EDIT:
The app is supposed to be a basic app where a user says something and the app replies.
But the original problem was that I could not get the string to display or TTS to work when my ViewController got it's string from another class/controller.
The answer in my below mentions that it was probably because my other class was calling my ViewController without the self.fliteController initialized.
How would I initialize the ViewController with self.fliteController initialized?
ViewController.m
- (void) pocketsphinxDidReceiveHypothesis:(NSString *)hypothesis recognitionScore:(NSString *)recognitionScore utteranceID:(NSString *)utteranceID {
NSString *strResult = hypothesis; //speech to text to string
ReplyManager* replyObject = [[ReplyManager alloc] init];
[replyObject speechResult:(NSString*)strResult viewController:self];
}
- (void) getReply:(NSString*)replyStr{
[self.fliteController say:replyStr withVoice:self.slt];
[self updateText:replyStr];
}
- (IBAction)updateText:(NSString*)replyStr{
labelOne.text = replyStr;
labelOne.adjustsFontSizeToFitWidth = YES;
labelOne.minimumFontSize = 0;
}
Any help will be great! Thanks!
ReplyManager.m
- (void) speechResult:(NSString*)strResult {
NSString *replystr;
NSString *greetings = #"Hi!";
NSString *sorry = #"Sorry I didn't catch that?";
ViewController* getReply = [[ViewController alloc] init];
if ([strResult isEqualToString:#"HELLO"])
{
replystr = greetings;
[getReply getReply:(NSString*)replystr];
}
else
{
replystr = sorry;
[getReply getReply:(NSString*)replystr];
}
}
EDIT 2:
viewDidLoad Method
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.fliteController = [[OEFliteController alloc] init];
self.slt = [[Slt alloc] init];
self.openEarsEventsObserver = [[OEEventsObserver alloc] init];
[self.openEarsEventsObserver setDelegate:self];
}
ViewController* getReply = [[ViewController alloc] init];
Here you init a new ViewController which does not have self.fliteController defined most likely. You need to reuse previos controller, for example like this:
[replyObject speechResult:(NSString*)strResult viewController:self];
So you can use already initialized viewController later. Overall it is better to initialize objects like viewController or replyController beforehand, not inside callback methods.
It sounds like a timing issue where you're trying to use fliteController before it's been initialized.
In your ViewController class, where do you assign a value to the fliteController property? In an initializer? -(void)viewDidLoad?
In ReplyManagerController add:
ViewController* getReply = [[ViewController alloc] init];
// Add these lines
NSLog(getReply.fliteController); // Is this nil?
[getReply.view layoutIfNeeded];
NSLog(getReply.fliteController); // Is it still nil?
Does the above fix the problem? If so, you're probably initializing fliteController in -(void)viewDidLoad. What's the result of the two NSLog statements?
Hello good people of Stackoverflow, i'm trying to make a function that gets a number of seconds and then create a local alert, here is what i have:
I created a class named manualtimer.h this is a Nsobject class.
In the manualTimer.h i have the following code:
-(void)tempoAlerta:(NSTimeInterval *)otempo;
In the manualTimer.M i have the following code:
-(void)tempoAlerta:(NSTimeInterval *)otempo {
UIApplication* myapp = [UIApplication sharedApplication];
UILocalNotification* localnote = [[UILocalNotification alloc]init];
localnote.fireDate = [NSDate dateWithTimeIntervalSinceNow:*otempo];
localnote.alertBody = #"Nice Alert";
localnote.timeZone = [NSTimeZone defaultTimeZone];
NSMutableArray *notifications = [[NSMutableArray alloc] init];
[notifications addObject:localnote];
myapp.scheduledLocalNotifications = notifications;
}
In my viewcontroller, i imported the manualTimer.h, but for some reason a cannot call the function tempoAlerta()
any ideas? xCode show no errors?
you must to instantiate a object of that class
manualTimer *obj = [[manualTimer alloc] init];
and then call that function
[obj tempoalerta:otempo];
What you have in your example code is defining a Method not a function. Functions are c style void anExampleFunction(int anArgument) and cannot be defined on objective-c classes.
How are you calling the method?
Your call should look something like this:
ManualTimer *timer = [ManualTimer new];
[timer temoAlerta:10];
Please look at this documentation for more information:
https://developer.apple.com/library/ios/referencelibrary/GettingStarted/Learning_Objective-C_A_Primer/#//apple_ref/doc/uid/TP40007594-CH1-SW11
I have a Cocoa app that uses automatic reference counting and does not use core-data (not document-based) and I want to be able to create multiple instances of a window I have defined in a nib file.
I currently have this in my AppDelegate:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// Insert code here to initialize your application
// for slight performance bump, we assume that users usually have 1 session open.
sessionWindowControllers = [[NSMutableArray alloc] initWithCapacity:1];
}
- (void) awakeFromNib {
// on start, we create a new window
[self newSessionWindow:nil];
}
- (IBAction)newSessionWindow:(id)sender {
SessionWindowController *session = [[SessionWindowController alloc] initWithWindowNibName:#"SessionWindow"];
//add it to the array of controllers
[sessionWindowControllers addObject:session];
[session showWindow:self];
}
SessionWindowController is a subclass of NSWindowController.
but when I run it, I get the runtime error
LayoutManagement[30415] : kCGErrorIllegalArgument:
_CGSFindSharedWindow: WID 11845 Jun 8 18:18:05 system-process LayoutManagement[30415] : kCGErrorFailure: Set a breakpoint #
CGErrorBreakpoint() to catch errors as they are logged. Jun 8
18:18:05 system-process LayoutManagement[30415] :
kCGErrorIllegalArgument: CGSOrderFrontConditionally: Invalid window
Is using NSMutableArray even a good way to manage multiple windows, or is there a better design pattern? Thanks!
Ans. kindly provided by Ben Flynn:
I put the
sessionWindowControllers = [[NSMutableArray alloc] initWithCapacity:1];
in applicationDidFinishLaunching, but since awakeFromNib is called first, we are trying to add an instance of session to the array before it even exists.
Solution: put array init inside the awakeFromNib before we make our first window.
- (void) awakeFromNib {
sessionWindowControllers = [[NSMutableArray alloc] initWithCapacity:1];
[self newSessionWindow:nil];
}
I'm running into a problem that I'm not sure how to solve. Let me just give some relevant code.
FrontpageViewController (viewDidLoad)
NewsFetcher *newsFetcher = [[NewsFetcher alloc] initWithURL:url];
newsFetcher.delegate = self;
[newsFetcher loadData];
NewsFetcher.h
#property (nonatomic, unsafe_unretained) id <NewsFetcherDelegate> delegate;
I'm using unsafe_unretained because I want my app to work with iOS 4 as well, while still using ARC for convenience.
NewsFetcher.m
- (id)initWithURL:(NSURL *)url {
self = [super init];
if (self) {
self.url = url;
self.receivedData = [[NSData alloc] init];
}
return self;
}
- (void)loadData {
NSLog(#"%#", self.delegate); // FrontpageViewController, as expected
NSURLRequest *request = [NSURLRequest requestWithURL:self.url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:15];
if (self.connectionInProgress)
[self.connectionInProgress cancel];
self.connectionInProgress = [[NSURLConnection alloc] initWithRequest:request
delegate:self
startImmediately:YES];
}
This all works fine. NewsFetcher conforms to the NSURLConnectionDelegate protocol, so the next method that's being called is connection:didReceiveData:. However, when I do another NSLog(#"%#", self.delegate) within that method, I get varied results (EXEC_BAD_ACCESS, NSCFDictionary, etc.). I think this means that my delegate property points to a released object, which is weird because it's supposed to be the view controller that's still on screen (and therefore couldn't have been released, right?).
How is my delegate available in one method, but not anymore in the next method? Does it have to do with the unsafe_unretained?
Delegate objects are not retained (by convention) by callers. The expectation is that the caller who set it on your object will retain it. Recommend you use the Instruments tool with zombies (and then with leaks) to see what's going on.
I am running into some serious memory leaks in one of my applications I am building. I have a UINavigatonController that is inside a UITabBarview. Inside the NavView is a MKMap view. When you click an accessory button on a callout a detail view is loaded. In that detail view I am trying to populate a table from a plist using a for(object in array) loop. The plist is an array of dictionaries. I am running though the dictionaries to find one with a key that is the title of the callout and then get an array from inside that dictionary. It all works fine in the simulaor but I am getting massive memory leaks doing it the way I am. Any Idea whats going on?
- (void)viewDidLoad {
self.title = #"Route Details";
NSString *path = [[NSBundle mainBundle] pathForResource:#"stopLocation" ofType:#"plist"];
holderArray = [[NSMutableArray alloc] initWithContentsOfFile:path];
[self getRouteArray];
routeDetails.delegate = self;
routeDetails.dataSource = self;
}
-(void)getRouteArray{
for (NSMutableDictionary *dictionary in holderArray) {
//NSString *stopName = [dictionary objectForKey:#"StopName"];
//NSString *stopName = [[NSString alloc] initWithString:[dictionary objectForKey:#"StopName"]];
BOOL testString = [currentRoute isEqualToString:[dictionary objectForKey:#"StopName"]];
if (testString) {
routeArray = [[NSMutableArray alloc] initWithArray:[dictionary objectForKey:#"RouteService"]];
}
}
}
- (void)dealloc {
[routeArray release];
[routeDetails release];
[super dealloc];
}
holderArray is an ivar and so is route array. As you can see I have tried a few ways of allocating the nstrings and arrays but all seem to yield the same leaks. According to the performance tool I am leaking from NSCFString, NSCFDictionary, and the NSCFArry. I released the routeArray in the dealloc and it works fine, but if I release holderArray it crashes whenever I go back to my map from the detail view. I guess I am just really unsure as to how to deal with the strings and dictionary used in the for loop.
Just to add the detail view is being created like so:
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control{
NSString *selectedRouteName = [NSString stringWithFormat:#"%#",view.annotation.title];
RouteDetailView *rdc = [[RouteDetailView alloc] initWithNibName:#"RouteDetailView" bundle:nil];
[rdc setCurrentRoute:selectedRouteName];
[self.navigationController pushViewController:rdc animated:YES];
[rdc release];
}
Sorry if any of the above is unclear. Let me know and I can try to rephrase it.
Will testString be true for at most one key in holderArray? If so, you should probably break out of the loop after setting routeArray. If not, then you may be setting routeArray multiple times, and all but the last array you assigned to it would be leaked.
Also, I don't see you releasing holderArray.