Get "[SceneKit] Error:" when set AVPlayer to SCNMaterial.diffuse.contents - scenekit

According Apple's docs, SCNMaterial.diffuse.contents can be a AVPlayer.
In this case material appear content of video.
Everything seems ok but I get several sceneKit error logs:
[SceneKit] Error: Could not get pixel buffer (CVPixelBufferRef)
Below is my code. Move [_player play] to viewWillAppear does't help.
- (void)viewDidLoad {
[super viewDidLoad];
self.boxNode = [self.sceneView.scene.rootNode childNodeWithName:#"box" recursively:YES];
NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingString:#"/VRF_SuLie.MP4"];
AVURLAsset *asset = [AVURLAsset assetWithURL:[NSURL fileURLWithPath:path]];
AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset];
_player = [AVPlayer playerWithPlayerItem:item];
self.boxNode.geometry.firstMaterial.diffuse.contents = _player;
}
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
[_player play];
}
How to avoid this error?

Related

changing up some code in 'DraggableViewBackground.m'

Github Source URL: https://github.com/cwRichardKim/RKSwipeCards
So, I need to change up some code in 'DraggableViewBackground.m'.
rather than an array of text as is on the stock source code, I need to create an array of images...
Stock section:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[super layoutSubviews];
[self setupView];
exampleCardLabels = [[NSArray alloc]initWithObjects:#"first",#"second",#"third",#"fourth",#"last", nil]; //%%% placeholder for card-specific information
loadedCards = [[NSMutableArray alloc] init];
allCards = [[NSMutableArray alloc] init];
cardsLoadedIndex = 0;
[self loadCards];
}
return self;
}
I have looked at various implementations of image array, but still comes up with some errors what I can't resolve.
this is my edited code for the array:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[super layoutSubviews];
[self setupView];
exampleCardGraphics = [[NSArray alloc]initWithObjects:00_quote#2x.png, 01_quote#2x.png,02_quote#2x.png,03_quote#2x.png,04_quote#2x.png,05_quote#2x.png,06_quote#2x.png,07_quote#2x.png,08_quote#2x.png,09_quote#2x.png,10_quote#2x.png,11_quote#2x.png,12_quote#2x.png,13_quote#2x.png,14_quote#2x.png,15_quote#2x.png,16_quote#2x.png,17_quote#2x.png,18_quote#2x.png,19_quote#2x.png,20_quote#2x.png,21_quote#2x.png,22_quote#2x.png,23_quote#2x.png,24_quote#2x.png,25_quote#2x.png,26_quote#2x.png,27_quote#2x.png,28_quote#2x.png,29_quote#2x.png,30_quote#2x.png,31_quote#2x.png,32_quote#2x.png,33_quote#2x.png,34_quote#2x.png,35_quote#2x.png,36_quote#2x.png,37_quote#2x.png,38_quote#2x.png,39_quote#2x.png,40_quote#2x.png,41_quote#2x.png,42_quote#2x.png,43_quote#2x.png,44_quote#2x.png,45_quote#2x.png,46_quote#2x.png,47_quote#2x.png,48_quote#2x.png,nil]; //%%% placeholder for card-specific information
loadedCards = [[NSMutableArray alloc] init];
allCards = [[NSMutableArray alloc] init];
cardsLoadedIndex = 0;
[self loadCards];
}
return self;
}
I get returned "Invalid suffix '_quote' on integer constant"
How would I resolve this to get images pulled into the array, and subsequently one image for each swipe card ?
I have changed a few other things, however only instance names, which have been changed accordingly in corresponding files, so the build still succeeds but I can't get the image array to work.
Please help!
Thanks.

Accessing a variable in multiple methods

Still a bit new and I am having some issues I was hoping someone could help with. I am trying to load a JSON string coming from my server into a collectionview in iOS6
I can pull in the data using a fetchedData method called from the viewDidLoad method and that part works fine. In the fetchedData method, I break out the JSON data and place it in NSDictionaries and NSArrays and can dump the correct data to the log to see it.
The problem is when I try and use any of the information elsewhere in my code such as get the amount of elements in any of hte arrays to use as a counter to fill the collectionview.
It may be that I am tired but I can't seem to get my head around this part. The declaration of many of the main variables was in the fetchedData method and I thought since the were declared there it could be the reason I could not see them elsewhere so I moved the declaration of the variables to the interface section and was hoping this would make the variables GLOBAL and the fetchedData method continues to work just fine, but nowhere else.
When I put in breaks in the cell definition area I can see in the debugger window the variables come up as empty.
I am not sure what sections of the code you may want to see so let me know and I can post them but maybe someone could give an example of how arrays and dictionary items can be accessed in multiple methods.
To avoid confusion and to expose my hodgepodge of code at this point anyway here is the .m file or at least most of it Please don't rip to hard on the coding style I have been trying anything I could think of and tore it up pretty hard myself and it was late.
#import "ICBCollectionViewController.h"
#import "ICBCollectionViewCell.h"
#import "ICBDetailViewController.h"
#interface ICBCollectionViewController () {
NSDictionary* json;
NSDictionary* title;
NSDictionary* shortDescrip;
NSDictionary* longDescrip;
NSDictionary* price;
NSDictionary* path;
NSDictionary* sKU;
NSDictionary* audiotrack;
NSDictionary* audiotracksize;
NSArray* titles;
NSArray* shortDescription;
NSArray* longDescription;
NSArray* prices;
// NSArray* paths;
NSArray* SKUs;
NSArray* audiotracks;
NSArray* audiotracksizes;
}
#end
/*
#interface NSDictionary(JSONCategories)
+(NSDictionary*)dictionaryWithContentsOfJSONURLString:(NSString*)urlAddress;
-(NSData*)toJSON;
#end
#implementation NSDictionary(JSONCategories)
+(NSDictionary*)dictionaryWithContentsOfJSONURLString:(NSString*)urlAddress
{
NSData* data = [NSData dataWithContentsOfURL: [NSURL URLWithString: urlAddress] ];
__autoreleasing NSError* error = nil;
id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (error != nil) return nil;
return result;
}
-(NSData*)toJSON
{
NSError* error = nil;
id result = [NSJSONSerialization dataWithJSONObject:self options:kNilOptions error:&error];
if (error != nil) return nil;
return result;
}
#end
*/
#implementation ICBCollectionViewController
#synthesize paths;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: imobURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
// Do any additional setup after loading the view.
}
- (void)fetchedData:(NSData *)responseData {
NSError* error;
//parse out the json data
json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
titles = [json objectForKey:#"title"]; //2
shortDescription = [json objectForKey:#"shortD"];
longDescription = [json objectForKey:#"longD"];
prices = [json objectForKey:#"price"];
self.paths = [json objectForKey:#"path"];
SKUs = [json objectForKey:#"SKU"];
audiotracks = [json objectForKey:#"audiotrack"];
audiotracksizes = [json objectForKey:#"audiotracksize"];
NSLog(#"paths: %#", paths); //3
// NSLog(#"shortDescrip: %#", shortDescription);
NSInteger t=7;
// 1) Get the latest loan
title = [titles objectAtIndex:t];
shortDescrip = [shortDescription objectAtIndex:t];
longDescrip = [longDescription objectAtIndex:t];
price = [prices objectAtIndex:t];
path = [paths objectAtIndex:t];
sKU = [SKUs objectAtIndex:t];
audiotrack = [audiotracks objectAtIndex:t];
audiotracksize = [audiotracksizes objectAtIndex:t];
//NSLog(title.count text);
//NSLog(title.allValues);
// 2) Get the data
NSString* Title = [title objectForKey:#"title"];
NSString* ShortDescrip = [shortDescrip objectForKey:#"shortD"];
NSString* LongDescrip = [longDescrip objectForKey:#"longD"];
NSNumber* Price = [price objectForKey:#"price"];
NSString* Path = [path objectForKey:#"path"];
NSString* SKU = [sKU objectForKey:#"SKU"];
NSString* AudioTrack = [audiotrack objectForKey:#"audiotrack"];
NSNumber* AudioTrackSize = [audiotracksize objectForKey:#"audiotracksize"];
/*************************HERE THE DATA EXISTS*******************************/
/******** Path = "XYXYXYXYXYXY" for example ********************************/
// 3) Set the label appropriately
NSLog([NSString stringWithFormat:#"Here is some data: Title: %# Path %# SKU: %# Price: %# Track %# Size %#",Title, Path, SKU, Price, LongDescrip, AudioTrackSize]);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
//DetailSegue
if ([segue.identifier isEqualToString:#"DetailSegue"]) {
ICBCollectionViewCell *cell = (ICBCollectionViewCell *)sender;
NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
ICBDetailViewController *dvc = (ICBDetailViewController *)[segue destinationViewController];
dvc.img = [UIImage imageNamed:#"MusicPlayerGraphic.png"];
}
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
NSLog(#"paths qty = %d",[paths count]);
return 20;
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier=#"Cell";
ICBCollectionViewCell *cell = (ICBCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
// paths = [json objectForKey:#"path"];
NSDictionary* path = [paths objectAtIndex:indexPath.row];
NSString* Path = [path objectForKey:#"path"];
// NSString* Path = [paths objectAtIndex:indexPath.row];
NSLog(#"%d",indexPath.row);
/***********************HERE IT DOES NOT**************************/
/******** Path = "" **********************************************/
NSLog(#"xxx");
NSLog(path);
NSLog(paths);
NSLog(Path);
NSLog(#"ZZZ");
Path=#"deepsleep";
NSLog(#"xxx");
NSLog(Path);
NSLog(#"ZZZ");
// paths = [json objectForKey:#"path"];
// NSString* Path = [path objectForKey:#"path"];
NSString *imagefile = [NSString stringWithFormat:#"https://imobilize.s3.amazonaws.com/glennharrold/data/%#/mid.png", Path];
NSLog(imagefile);
NSURL *url1=[NSURL URLWithString:imagefile];
dispatch_async(kBgQueue, ^{
NSData *data1 = [NSData dataWithContentsOfURL:url1];
cell.imageView.image =[[UIImage alloc]initWithData:data1];
});
return cell;
}
#end
Try breaking out the JSON data and sorting it in the appDelegate. If you declare public variables there #property (nonatomic, strong) NSDictionary *myDict etc., then you can access those variables by importing your appDelegate and using the following code:
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSDictionary *newDict = appDelegate.myDict;
Otherwise, you can store the information in a singleton, or in the root view controller. The key is to store your variables in a class that won't be deallocated. Most often, it is a bad idea to use a viewController for that purpose-- they have a tendency to be navigated away from, which deallocates the memory and gets rid of your variables. Google "model-view-controller" for more info.
I found out what the main issue was it the ViewDidLoad method I was using a background activity to get the JSON data from my server and as that process was running the foreground was also being processed and since the rest of the code was based on a value returned when the background process finished the data was actually null so all data based on that single piece were also null and it looked as if it was not available. Once I made the process run in the foreground all the variable started having values.
Thanks for your assistance with this

ivar is releasing under ARC - how do I retain it for use in another method?

I have been struggling with something for weeks and it has brought a real halt to my progress. I have asked a question a few times on SO, people have been helpful but no-one has cracked what I am doing wrong. It seems a fairly simple thing so hopefully someone out there will have a lightbulb moment and solve this. I am implementing a TWRequest, the result is coming back in a dictionary, I am looping through the results to extract a part of the tweet and creating an array of these 'text' components. Straight adter the loop through I am peinting the log of the array - _twitterText and it prints fine. Staright after this method is complete it seems as though _twitterText is being dumped. I have created it in my .h file as a strong property and created an ivar in viewdidload. Still no joy. how do I retain this array to use in another Method?
Here is my .h file....
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import "CustomCell.h"
#import "AppDelegate.h"
#import <Twitter/Twitter.h>
#interface MyViewController : UITableViewController <CLLocationManagerDelegate>
{
CLLocationManager *here;
}
#property(strong) NSDictionary *dict;
#property(strong) CLLocationManager *here;
#property (strong, nonatomic) NSMutableArray *twitterText;
- (void)fetchTweets;
#end </p>
Here is my .m implementation file......
#import "MyViewController.h"
#interface MyViewController ()
#end
#implementation MyViewController
#synthesize dict;
#synthesize twitterText = _twitterText;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_twitterText = [[NSMutableArray alloc] init];
here = [[CLLocationManager alloc] init];
here.delegate = self;
[here startUpdatingLocation];
AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
NSLog(#"phrase carried over is %#", delegate.a);
[self fetchTweets];
}
- (void)fetchTweets
{
TWRequest *request = [[TWRequest alloc] initWithURL:[NSURL URLWithString:
#"http://search.twitter.com/search.json?q=%40wimbledon"]
parameters:nil requestMethod:TWRequestMethodGET];
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
if ([urlResponse statusCode] == 200)
{
// The response from Twitter is in JSON format
// Move the response into a dictionary and print
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
//NSLog(#"Twitter response: %#", dict);
NSArray *results = [dict objectForKey:#"results"];
//Loop through the results
for (NSDictionary *tweet in results) {
// Get the tweet
NSString *twittext = [tweet objectForKey:#"text"];
// Save the tweet to the twitterText array
[_twitterText addObject:twittext];
}
NSLog(#"MY ************************TWITTERTEXT************** %#", _twitterText);
}
else
NSLog(#"Twitter error, HTTP response: %i", [urlResponse statusCode]);
}];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
// Return the number of rows in the section.
return 5;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"MyCell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
//cell.venueDetails.text = [_twitterText objectAtIndex:indexPath.row];
NSLog(#"MY ************************OTHER BIT THAT WONT PRINT************** %#", _twitterText);
return cell;
}
So the issue here is that your completion handler that you pass to -[TWTweet performRequestWithHandler:] isn't going to (can't) fire until the network connection is complete and the server responds to your request. That could take hundreds of milliseconds or even seconds to complete. (Or it may never happen).
Meanwhile while that is happening, the UITableView wants to draw itself and so will ask you how many sections/rows you have and then will ask you for a cell for each row. So when the table view asks, you should return the actual number of rows you have to draw at that time:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.twitterText count]; // the actual number of rows we have right now
}
So then the next step you need is to reload the table when your data is actually in from the server. That will prompt your table view to ask again for the number of sections and rows, and then ask for cells for each section and row. So somewhere in your completion block after you've processed all your data you will need to do this:
dispatch_async(dispatch_get_main_queue(), ^{
// you'll need an outlet to the UITableView
// here I assume you call that 'tableView'
// then just ask it to reload on the main thread
[self.tableView reloadData];
});
I hope that helps?

CoreData leaks with fetched results arrays

I'm using CoreData to store objects like cars, trips, data recorded from GPS, etc.
When I fetch what I want to show a list of trips, some stats for a trip, or add a new car in my settings view controller, I use pretty much this kind of request:
- (void)getDataTrip
{
// Fetched data trips.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"DataTrip" inManagedObjectContext:[self managedObjectContext]];
[fetchRequest setEntity:entity];
// Set predicate and sort orderings...
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"timestamp" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[sortDescriptor release];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"idTrip = %#", self.idTrip];
[fetchRequest setPredicate:predicate];
// Execute the fetch -- create a mutable copy of the result.
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[self.managedObjectContext executeFetchRequest:fetchRequest error:&error] mutableCopy];
if (mutableFetchResults == nil) {
// Handle the error.
NSLog(#"failed with error: %#", error);
}
// Set the array.
[self setDataTripArray:mutableFetchResults];
// Memory management.
[fetchRequest release];
[mutableFetchResults release];
}
Sometimes, I have leaks when I do the [self setDataTripArray:mutableFetchResults]; and sometimes not. In this case, when I get the data for a trip, it leaks all the time when I use the navigation controller to come back to the root view controller (displaying a list of trips), and/or when I change tab.
Anyway, it just leaks and it's all the time coming from fetching data from CoreData, and give this array to my local array var.
Please let me know if you see how to fix this! It made the app crash after a while.
Thanks!
SOLUTION
I found that I do a retain on my object dataTripArray object when creating another UIViewController that I use to create graphs for my scroll view.
- (void)loadScrollViewWithPage:(int)page
{
if (page < 0)
return;
if (page >= kNumberOfPages)
return;
// Replace the placeholder if necessary.
GraphController *controller = [self.graphControllers objectAtIndex:page];
if ((NSNull *)controller == [NSNull null])
{
controller = [[GraphController alloc] initWithPageNumber:page data:[self.dataTripArray retain]];
[self.graphControllers replaceObjectAtIndex:page withObject:controller];
[controller release];
}
// Add the controller's view to the scroll view.
if (controller.view.superview == nil)
{
CGRect frame = _scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
controller.view.frame = frame;
[self.scrollView addSubview:controller.view];
}
}
I just removed the retain and the leak is no longer coming up. Fixed!

Saving arrays of iOS Apps

I would like to know how to save arrays of my iOS app. I used a method, but it only saved on my iPod Touch. I'd tested on iPad and it didn't work.
What I need is a code to save my app array on any device...
Anyone can help me?
Here is the code:
myAppViewController.h:
- (NSString *)GetApplicationDocumentsDirectory;
- (void)applicationWillTerminate:(NSNotification *)notification;
myAppViewController.m:
-(NSString*) GetApplicationDocumentsDirectory {
static NSString* documentsDirectory = nil;
if (documentsDirectory == nil) {
documentsDirectory = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES)
objectAtIndex:0] retain];
}
NSString *fullFileName = [NSString stringWithFormat:#"%#/TarefasSalvas.plist", documentsDirectory];
return fullFileName;
}
- (void)applicationWillTerminate:(NSNotification *)notification{
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:lisTitulos];
[array addObject:lisImagens];
[array addObject:lisData];
[array addObject:lisDetalhes];
[array writeToFile:[self GetApplicationDocumentsDirectory] atomically:YES];
}
- (void)viewDidLoad {
[super viewDidLoad];
NSString *filePath = [self GetApplicationDocumentsDirectory];
//if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
if (array != nil){
lisTitulos = [array objectAtIndex:0];
lisImagens = [array objectAtIndex:1];
lisData = [array objectAtIndex:2];
lisDetalhes = [array objectAtIndex:3];
}
else {
NSDate *date = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setLocale:[NSLocale currentLocale]];
[dateFormat setDateFormat:#"dd/MM/YYYY"];
NSString *dateNow = [dateFormat stringFromDate:date];
lisTitulos = [[NSMutableArray alloc] initWithObjects:#"Titulo",nil];
lisImagens = [[NSMutableArray alloc] initWithObjects:#"0.png",nil];
lisData = [[NSMutableArray alloc] initWithObjects:dateNow,nil];
lisDetalhes = [[NSMutableArray alloc] initWithObjects:#"",nil];
}
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(applicationWillTerminate:) name:UIApplicationWillTerminateNotification object:app];
}
Thanks
It is possible that you're just sending the app to the background and not terminating them. On such occasion, applicationWillTerminate: will not be called. That seems to be the likely cause as the rest of the code looks fine.
And your GetApplicationDocumentsDirectory seems a bit strangely named as it gets the path to the file in which the array is stored. In addition to that,
NSString *fullFileName = [NSString stringWithFormat:#"%#/TarefasSalvas.plist", documentsDirectory];
is not the correct way of getting the file path. You should use thestringByAppendingPathComponent: method on documentsDirectory like this,
NSString *fullFileName = [documentsDirectory stringByAppendingPathComponent:#"TarefasSalvas.plist"];
It would also make sense to declare fullFileName as the static variable rather than documentsDirectory.
Thanks #Deepak.
After u giving me the hint about making the Log Alerts on Debugging, I noticed that the iPad is killing the App and then the app can't call the applicationWillTerminate: method as you mentioned before.
So I solved the Problem changing my code to:
- (void)applicationWillTerminate:(NSNotification *)notification{
[self SavingStatus];
}
-(void)SavingStatus {
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:lisTitulos];
[array addObject:lisImagens];
[array addObject:lisData];
[array addObject:lisDetalhes];
[array writeToFile:[self GetApplicationDocumentsDirectory] atomically:YES];
}
As you can see, I created a method that I call on applicationWillTerminate: method and everytime the app reload the Table data:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
...
[self SavingStatus];
return cell;
}
By this way, even if your device Kill the App before it Close normally, the informations will be saved anyway =D.
Thanks again to #Deepak
and everybody who replied me.

Resources