iOS access a single instance of an object from two different classes - instance

Is it possible to create an instance of an object in class A and access that same instance of the object from class B? I am trying to develop an app that creates a TCP Socket using NSInputStream and NSOutputStream and need more than one class to be able to access it.
Thank you,
Travis Elliott
edit
Here is the code I am working with. Its a program that deals with socket connections. I basically need to be able to communicate to the same socket from my appDelegate and View controller. Here is the code I have based on your help. I am using the appDelegate as the control(D in your example), perhaps I cannot do this. CommunicationHub is the class I need to control the same instance of from both AppDelegate and ViewController.
AppDelegate.h
#import <UIKit/UIKit.h>
#import "ViewController.h"
#import "CommunicationHub.h"
#interface AppDelegate : UIResponder <UIApplicationDelegate>{
ViewController *viewController;
CommunicationHub *cHub;
}
#property (strong, nonatomic) UIWindow *window;
#property (strong, retain) ViewController *viewController;
#property (strong, retain) CommunicationHub *cHub;
-(void)CreateInstances;
#end
AppDelegate.m
#import "AppDelegate.h"
#import "ViewController.h"
#implementation AppDelegate
#synthesize viewController;
#synthesize cHub;
#synthesize window = _window;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self CreateInstances];
// Override point for customization after application launch.
return YES;
}
-(void)CreateInstances{
NSLog(#"Inside CreateInstances");
CommunicationHub *cHub = [[CommunicationHub alloc] init];
viewController = [[ViewController alloc] init];
[viewController initWithcHub:cHub];
NSLog(#"ID of cHub in AppDelegate is %i", cHub);
}
- (void)applicationWillResignActive:(UIApplication *)application
{
NSLog(#"Application Will Resign Active");
[cHub disconnect];
}
#end
ViewController.h
#import <UIKit/UIKit.h>
#import "CommunicationHub.h"
#interface ViewController : UIViewController
{
CommunicationHub *cHub;
}
#property (strong, nonatomic) IBOutlet UITextField *IPAddress;
#property (strong, nonatomic) IBOutlet UITextField *PortNumber;
- (IBAction)goAwayKeyBoard:(id)sender;
- (IBAction)touchBackground:(id)sender;
-(void) initWithcHub:(CommunicationHub *)ptr;
- (IBAction)connectSocket:(id)sender;
- (IBAction)disconnectSocket:(id)sender;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize IPAddress;
#synthesize PortNumber;
-(void) initWithcHub:(CommunicationHub *)ptr
{
cHub = [[ptr retain]init];
NSLog(#"id of cHub in ViewController is %i", cHub);
}
- (IBAction)connectSocket:(id)sender
{
//Called by button on UI.
int portNumber = [PortNumber.text intValue];
[cHub Connect:(int *)portNumber ipAddress:(IPAddress.text)];
}
- (IBAction)disconnectSocket:(id)sender
{
//Called by button on UI.
[cHub disconnect];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[self setIPAddress:nil];
[self setPortNumber:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} else {
return YES;
}
}
-(IBAction)goAwayKeyBoard:(id)sender{
[self resignFirstResponder];
}
- (IBAction)touchBackground:(id)sender {
[IPAddress resignFirstResponder];
[PortNumber resignFirstResponder];
}
#end
CommunicationHub.h
#import <UIKit/UIKit.h>
NSInputStream *inputStream;
NSOutputStream *outputStream;
#interface CommunicationHub : NSObject <NSStreamDelegate>
- (void)Connect:(int *)port ipAddress:(NSString *)ipAddress;
- (void) disconnect;
#end
CommunicationHub.m
#import "CommunicationHub.h"
#implementation CommunicationHub
- (void)Connect:(int *)port ipAddress:(NSString *)ipAddress
{
NSLog(#"inside connect method");
if ([inputStream streamStatus] == 0 ||[inputStream streamStatus] == 5 ||[inputStream streamStatus] == 6 ||[inputStream streamStatus] == 7)
{
NSString *myString = ipAddress;
CFStringRef *myCFString = (__bridge CFStringRef)myString;
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, myCFString, port, &readStream, &writeStream);
inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
}
}
- (void) disconnect
{
NSLog(#"inside disconnect method");
if (inputStream != nil) {
if ([inputStream streamStatus] == 2) {
NSLog(#"Disconnecting Streams");
[inputStream close];
[outputStream close];
}else {
NSLog(#"Stream is not Open");
int status = [inputStream streamStatus];
NSLog(#"Stream Status is %i", status);
}
}else {
NSLog(#"Input Stream equals Nil");
}
}
#end

To make it long:
Assuming you have class A, B and C.
C needs to be accessible, from both A and B.
Now, let's assume we have controller D, which instantiates both A and B.
Have D instantiate C first, and store it in a variable.
C *C_Class = [[[C alloc] init] autorelease];
Next, instantiate A and B with C (I'm assuming 'retain properties' here)
self.A_Class = [[[A alloc] initWithC:C_Class] autorelease];
self.B_Class = [[[B alloc] initWithC:C_Class] autorelease];
In both classes, you need the instance method:
- (id)initWithC:(C *)C_Class;
and in the .m file:
- (id)initWithC:(C *)C_Class {
C_C = [C_Class retain]; //Assuming a regular instance variable
}
- (void) dealloc {
[C_C release]; //All that is retained, must be released.
}
From this moment on, you have access to that one instance of Class C in classes A and B, via the name 'C_C'.
Now, please mind that this is just written from the back of my head and prone to have errors, but it SHOULD be alright.
I hope it helps :)
Edit: Since the OP seems to have trouble with these code fragments, I'll add a more complete code.
Let's start with the control class 'D'.
D.h:
#import "A.h"
#import "B.h"
#interface D : NSObject
-(void)CreateInstances;
#property (strong, retain) A *A_Class;
#property (strong, retain) B *B_Class;
#end
D.m:
#import "D.h"
#import "C.h"
#implementation D
-(void)CreateInstances {
C *C_Class = [[C alloc] init] autorelease];
self.A_Class = [[[A alloc] initWithC:C_Class] autorelease];
self.B_Class = [[[B alloc] initWithC:C_Class] autorelease];
}
#end
A.h (B.h mirrors this behavior, maybe consider using a superclass for both)
#import "C.h"
#interface A : NSObject {
C *C_Class; //Class Reference to the C-Object
}
-(id) initWithC:(C *)ptr; //Initialization method, which takes a 'C'-Object.
#end;
A.m
#import "A.h"
#implementation A
- (id) initWithC:(C *)ptr {
C_Class = [ptr retain]; //So the object doesn't get released prematurely.
}
- (void) dealloc {
[C_Class release]; //To avoid memory leaks.
}
#end
Now, please remember, that I wrote this off the top of my head and didn't run it through a compiler, but it SHOULD work, save typos and the likes.
Another edit:
After the OP added his own code, I will post relevant bits of 'corrected' code here.
AppDelegate.m
-(void)CreateInstances{
NSLog(#"Inside CreateInstances");
cHub = [[CommunicationHub alloc] init]; //We're using the instance variable. Not the local one.
viewController = [[ViewController alloc] initWithcHub:cHub];
//[viewController initWithcHub:cHub]; //You may want to rethink your function names.
NSLog(#"ID of cHub in AppDelegate is %i", cHub);
}
ViewController.m
//If a method names STARTS with 'init', it SHOULD initialize the object.
-(id) initWithcHub:(CommunicationHub *)ptr
{
self = [super init]; //Calls the 'init' from the parent class.
if(self) {
cHub = [ptr retain]; //Just retain. After all, the object IS initialized already.
NSLog(#"id of cHub in ViewController is %i", cHub);
}
return self;
}
- (void) dealloc {
[cHub release]; //Basic rule of memory management: ALL that is retained, must be released. In dealloc, at latest.
}
- (IBAction)connectSocket:(id)sender
{
//Called by button on UI.
//Do not pass a pointer to anything, unless you mean to use a pointer.
[cHub Connect:[PortNumber.text intValue] ipAddress:(IPAddress.text)];
}
The rest should be somewhat correct, or at least not subject of this question.

Related

Null variable in Objective C

I'm developing an iOS application and I'm having some problems when I try to save data.
My code is:
TuplaUsuario:
It is a class where I save user data. In that case, I use mensaje variable, so here is its code:
//TuplaUsuario.h:
#interface TuplaUsuario : NSObject
{
NSMutableString* mensaje;
}
#property NSMutableString* mensaje;
#end
//TuplaUsuario.m:
#import "TuplaUsuario.h"
#implementation TuplaUsuario
#synthesize mensaje;
- (id)initWithString:(NSString *)identifier {
if ( self = [super init] ) {
mensaje = [[NSMutableString alloc] initWithString:identifier];
}
return self;
}
#end
WebService:
It is a class where I communicate with a Web Service.
//WebService.h:
#import "TuplaUsuario.h"
#interface WebService : NSObject {
// Some other data
NSMutableString* message;
TuplaUsuario* usuario;
}
//Declaration of methods
#end
//WebService.m:
#import "WebService.h"
#import "AppDelegate.h"
#implementation WebService
- (id)init:(NSString *)identifier {
self = [super init];
usuario = [[TuplaUsuario alloc] initWithString:#""];
return self;
}
- (void) processComplete: (BOOL)success {
[[self delegate] processSuccessful:success];
AppDelegate* myAppDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
[myAppDelegate setUsuarioActual:usuario];
}
- (void)login:(NSString *)username password:(NSString *)password
{
//Connection with Web Service
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData {
NSDictionary* jsonArray=[NSJSONSerialization
JSONObjectWithData:theData
options:0
error:nil];
message = [jsonArray objectForKey:#"message"];
[usuario setMensaje:message];
}
AppDelegate:
//AppDelegate.h:
#import <UIKit/UIKit.h>
#import "TuplaUsuario.h"
#interface AppDelegate : UIResponder <UIApplicationDelegate>
{
Boolean rememberMe;
TuplaUsuario* usuarioActual;
}
#property (strong, nonatomic) UIWindow *window;
#property (retain) TuplaUsuario* usuarioActual;
#end
//AppDelegate.m:
#import "AppDelegate.h"
#implementation AppDelegate
#synthesize usuarioActual;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
usuarioActual = [[TuplaUsuario alloc] initWithString:#""];
return YES;
}
PROBLEM
In WebService, method connection didReceiveData, if I print message variable, it has the correct value, but if I print [usuario mensaje] it prints (null).
Where's my error?
SOLVED
The problem was in my ViewController and init method of WebService. I called init instead of initWithString:
ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
wSProtocol = [[WebService alloc] initWithString:#""]; //Variable of type WebService
}
WebService
- (id)initWithString:(NSString *)identifier {
self = [super init];
usuario = [[TuplaUsuario alloc] initWithString:#""];
return self;
}
Maybe because this method:
- (id)init:(NSString *)identifier {
if ( self = [super init] ) {
mensaje = [[NSMutableString alloc] init];
}
return self;
}
is never called, since you use:
usuario = [[TuplaUsuario alloc] init];
but is still wonder why you pass identifier into the method and never use it. I think you should make it like this:
mensaje = [[NSMutableString alloc] initWithString:identifier];

UIWebView: Delegate won't be called

I try to calculate the size of a UIWebView with a given content, but without showing the view. I only need to know the size.
My Problem: When I execute the code, the delegate of the UIWebView isn't called. Why?
MessageSizeCaluclator.h
#import < Foundation/Foundation.h>
#class Message;
#interface MessageSizeCaluclator : NSObject <UIWebViewDelegate>
- (id)initWithMessage:(Message*)message;
- (void)saveSize;
#end
MessageSizeCaluclator.m
#import "Message.h"
#import "MessageSizeCaluclator.h"
#interface MessageSizeCaluclator () <UIWebViewDelegate>
#property (strong, nonatomic) Message* message;
#property (strong, nonatomic) UIWebView* webView;
#end
#implementation MessageSizeCaluclator
#synthesize message = _message;
#synthesize webView = _webView;
- (id)initWithMessage:(Message*)message
{
self = [super init];
if (self) {
_message = message;
// WebView
_webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
_webView.delegate = self;
}
return self;
}
- (void)saveSize
{
NSLog(#"%s message = %#", __PRETTY_FUNCTION__, _message.text);
[_webView loadHTMLString:[NSString stringWithFormat:#"<div style='font-family:Helvetica;font-size:13px;'>This is a test</div>", _message.text]
baseURL:nil];
}
#pragma mark - Web view delegate
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
NSLog(#"%s", __PRETTY_FUNCTION__);
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
NSLog(#"%s", __PRETTY_FUNCTION__);
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSLog(#"%s", __PRETTY_FUNCTION__);
}
#end
Implementation
MessageSizeCaluclator* messageSizeCalculator = [[MessageSizeCaluclator alloc] initWithMessage:message];
[messageSizeCalculator saveSize];
Add your UIWebView to some UIView, make its frame offscreen (so users can't see it). The delegate methods won't be called if UIWebView is not in the view hierarchy of the app.

how to delegate with an IBAction between two different UIViewController

I'm just trying to understand how delegate works and I'm in troubles.
I have two classes (both UIViewController) connected into the storyboard, the first one (ViewController.h/m) hold a TableView with cells and the second one (AddNameViewController.h/m) simply hold a TextField (where I want to write) and a button (Add Name)
as you surely understand I want the button pressed to send to the TableView what is written into the TextField, pretty simple.
And since I have two different Controllers and an Array containing the data holds by the tableview, I want to connect them with a delegate (just to learn it).
here is some code:
ViewController.h
#import "AddNameViewController.h"
#interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, AddNameViewControllerDelegate>
#property (strong, nonatomic) NSMutableArray *array;
#end
ViewController.m
#import "ViewController.h"
#import "AddNameViewController.h"
#inferface ViewController ()
#end
#implementation ViewController
#synthesize array;
-(void)addStringWithString:(NSString*)string
{
[self.array addObject:string];
NSLog(#"%#", array);
}
-(void)viewDidLoad
{
AddNameViewController *anvc = [[AddNameViewController alloc] init];
anvc.delegate = self;
array = [[NSMutableArray alloc] initWithObjects:#"first", #"second", nil];
NSLog(#"%#", array);
[super viewDidLoad];
}
-(NSInteger)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSindexPath*)indexPath
{
static NSString *simpleTableIdentifier = #"RecipeCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.textLabel.text = [array objectAtIndex:indexPath.row];
return cell;
}
#end
AddNameViewController.h
#protocol AddNameViewControllerDelegate <NSObject>
-(void)addStringWithString:(NSString*)string;
#end
#interface AddNameViewController : UIViewController
#property (weak, nonatomic) id <AddNameViewControllerDelegate> delegate;
#property (weak, nonatomic) IBOutlet UITextField *myTextField;
-(IBAction)add:(id)sender;
#end
finally the AddNameViewController.m
#import "ViewController.h"
#interface AddNameViewController ()
#end
#implementation AddNameViewController
#synthesize myTextField, delegate;
-(id)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
-(void)viewDidLoad
{
[super viewDidLoad];
}
-(IBAction)add:(id)sender
{
[self.delegate addStringWithString:self.myTextField.text];
// I've also tried with this but nothing --> [self.delegate addStringWithString:#"aa"];
}
#end
The array is initialized properly, no errors, no warnings, no crashes, simply seems like the method "addStringWithString" is not even called, because is not even NSLog anything.
obviously everything in connected in the storyboard, methods and outlets, thanks for your help.
in interface builder of AddNameViewController, did you connect the button event (Touch Up inside) into the action -(IBAction)add:(id)sender ?
also try this
-(IBAction)add:(id)sender
{
if([self.delegate respondsToSelector:#selector(addStringWithString:)]) {
[self.delegate addStringWithString:self.myTextField.text];
}
// I've also tried with this but nothing --> [self.delegate addStringWithString:#"aa"];
}

Why is Xcode saying my class implementation is incomplete?

I have created a singleton for my MusicBackground. And I receive a line code of imcomplete implementation of this line #implementation MyBgMusic. Can anyone tell me why ? Below is the code:
#import "MyBgMusic.h"
static MyBgMusic *sharedMyManager = nil;
#implementation MyBgMusic
#synthesize player,playBgMusic;
#pragma mark -
#pragma mark Singleton Methods
+ (MyBgMusic*)sharedInstance {
static MyBgMusic *_sharedInstance;
if(!_sharedInstance) {
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedInstance = [[super allocWithZone:nil] init];
});
}
return _sharedInstance;
}
+ (id)allocWithZone:(NSZone *)zone {
return [self sharedInstance];
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
#if (!__has_feature(objc_arc))
- (id)retain {
return self;
}
- (unsigned)retainCount {
return UINT_MAX; //denotes an object that cannot be released
}
- (id)autorelease {
return self;
}
- (void)dealloc
{
[MyBgMusic release];
[playBgMusic release];
[player release];
[super dealloc];
}
#endif
#pragma mark -
#pragma mark Custom Methods
- (void)viewDidLoad
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"music" ofType:#"mp3"];
self.player=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
player.delegate = self;
[player play];
player.numberOfLoops = -1;
[super viewDidLoad];
}
#end
For the M file, below is the code:
#import <Foundation/Foundation.h>
#import <AVFoundation/AVAudioPlayer.h>
#interface MyBgMusic : UIViewController <AVAudioPlayerDelegate> {
AVAudioPlayer *player;
UIButton *playBgMusic;
}
#property (nonatomic, retain) IBOutlet AVAudioPlayer *player;
#property (nonatomic, retain) IBOutlet UIButton *playBgMusic;
+ (id)sharedManager;
-(IBAction) toggleMusic;
#end
And how do I reference to my toggle button: Below is the code :
- (IBAction)toggleMusic {
if ([self.player isPlaying] == YES) {
[self.player stop];
} else {
[self.player play];
}
self.playBgMusic.enabled = YES;
}
It means that your MyBgMusic class isn't doing everything it promised to do in its header file, which includes being a UIViewController and implementing the AVAudioPlayerDelegate protocol. I'm not familiar with exactly what the AVAudioPlayerDelegate is, but it's quite possible that your class doesn't implement all of the required methods.
Also, you're declaring methods +(id)sharedManager and -(IBAction)toggleMusic, but I don't see them anywhere in the implementation file. That would be a case of promising something in the header and not implementing it in the class.
It would help if you posted the actual error message.
That error means your #implementation section does not contain everything described in the #interface section.
I can see two problems.
First you need to place this code:
- (IBAction)toggleMusic {
...
}
Somewhere in between #implementation and #end.
And you also need to rename the line + (MyBgMusic*)sharedInstance to + (id)sharedManager.
EDIT:
To access the toggle music method elsewhere in your code, you would do:
[[MyBgMusic sharedManager] toggleMusic];
Your +(id)sharedManagerimplementation is called +(id)sharedInstance. Just guessing, but it seems they are supposed to do the same.

EXC_BAD_ACCESS when I change moviePlayer contentURL

In few words, my application is doing that :
1) My main view (RootViewController) has a buton when I tap on it, it displays the player (PlayerViewController) :
2) In my Player, I initialize the video I want to play
-> It's working good, my movie is display
My problem :
When I go back to my main view :
And I tap again on the button, I get a *Program received signal: “EXC_BAD_ACCESS”.*
If I comment self.player.contentURL = [self movieURL]; it's working, but when I let it, iI have this problem.
I read that it's due to null pointer or memory problem but I don't understand why it's working the first time and not the second time. I release my object in dealloc method.
Thanks for your help !
Bruno.
Here is my code :
Root View Controller
RootViewController.h
#import <UIKit/UIKit.h>
#import "PlayerViewController.h"
#interface RootViewController : UIViewController {
IBOutlet UIButton * myButton;
}
#property (nonatomic,retain) IBOutlet UIButton * myButton;
-(IBAction)displayPlayer:(id)sender;
- (void) returnToRoot: (PlayerViewController *) controller;
#end
RootViewController.m
#import "RootViewController.h"
#implementation RootViewController
#synthesize myButton;
-(IBAction)displayPlayer:(id)sender
{
PlayerViewController *playerViewController = [[PlayerViewController alloc] initWithNibName:#"PlayerViewController" bundle:nil];
playerViewController.delegate = self;
playerViewController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController: playerViewController animated: YES];
[playerViewController release];
}
- (void) returnToRoot: (PlayerViewController *) controller
{
[self dismissModalViewControllerAnimated: YES];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
- (void)dealloc {
[super dealloc];
}
#end
Player View Controller
PlayerViewController.h
#import <UIKit/UIKit.h>
#import <MediaPlayer/MPMoviePlayerController.h>
#protocol PlayerViewControllerDelegate;
#interface PlayerViewController : UIViewController {
UIView *viewForMovie;
MPMoviePlayerController *player;
}
#property (nonatomic, assign) id <PlayerViewControllerDelegate> delegate;
#property (nonatomic, retain) IBOutlet UIView *viewForMovie;
#property (nonatomic, retain) MPMoviePlayerController *player;
- (NSURL *)movieURL;
-(IBAction)goBackToRoot:(id)sender;
#end
#protocol PlayerViewControllerDelegate
- (void) returnToRoot: (PlayerViewController *) controller;
#end
PlayerViewController.m
#import "PlayerViewController.h"
#implementation PlayerViewController
#synthesize player;
#synthesize viewForMovie;
#synthesize delegate;
- (void)dealloc {
[super dealloc];
[player release];
[viewForMovie release];
}
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"viewDidLoad");
self.player = [[MPMoviePlayerController alloc] init];
[self.player autorelease];
self.player.view.frame = self.viewForMovie.bounds;
self.player.view.autoresizingMask =
UIViewAutoresizingFlexibleWidth |
UIViewAutoresizingFlexibleHeight;
[self.viewForMovie addSubview:player.view];
self.player.contentURL = [self movieURL];
[self.player play];
}
-(NSURL *)movieURL
{
NSBundle *bundle = [NSBundle mainBundle];
NSString *moviePath =
[bundle
pathForResource:#"myVideo"
ofType:#"mp4"];
if (moviePath) {
return [NSURL fileURLWithPath:moviePath];
} else {
return nil;
}
}
-(IBAction)goBackToRoot:(id)sender{
[self.delegate returnToRoot: self];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
#end
Problem
The second time I call "displayPlayer" I had the EXC_BAD_ACCESS
I solved it !!!
I look on the MPMoviePlayerController to see what kind of variable is contentURL
(NSURL *)contentURL
It means I have also to liberate it.
I do that in my dealloc method putting a nil value:
-(void) dealloc {
[super dealloc];
self.player.contentURL = nil;
[player release];
[viewForMovie release];
}
If I comment self.player.contentURL =
[self movieURL]; it's working, but
when I let it, iI have this problem.
In that case, how is contentURL declared? Does the #property definition include copy or retain?