"Dead Store" Warning in Xcode - ios

I am getting a dead store warning when I analyze my project but the project does not crash.
Here is what I am doing
NSString *graphUrl = nil;
if ([graphArray count] == 1)
{
objTrial = [graphArray objectAtIndex:0];
graphUrl = #"http://chart.apis.google.com/chart?cht=s:nda&chf=bg,s,FFFFFF&chs=";
graphUrl = [graphUrl stringByAppendingString:#"&chd=t:"];
graphUrl = [graphUrl stringByAppendingString:objTrial.highValue];// get the dead store error here
}
else
{
//someother operation is done and a value is loaded to aURL
}
I get a dead store warning as mentioned in the code.. How can I prevent this?
It would be great if someone could help me out in this

The warning is telling you that the store that you do in the first line gets thrown away (i.e assigning an empty string to the variable and then reassigning it afterwards without using the original value). Just change the first line to the following and the warning should go away:
NSString *aUrl;
Edit:
you should change the line where you use it also:
aURL = [aValue copy];

"dead store" means something that's not used, or rather something useless.
You get it when you have a variable defined that you never do anything with. So, the Analyzer tells you that you have wasted some storage.
Here you haven't used the aUrl object after assigning it.
It won't cause any problems other than a few bytes of wasted memory. Of course if it's a large object that could be more.
Perhaps someone could chip in with knowledge of compilers, as compiler optimization might take care of dead stores in any case.

Dead Store is a value that is assigned but never used. There is nothing to worry about it. But if you can't control yourself from worrying ;-) you can change your code to,
NSString aUrl = nil;
if ([anArray count] == 1) {
// a value is store in aValue
// then that value is appended to aURL
aURL = [aURL stringByAppendingString:aValue];
} else {
aUrl = #"";
//someother operation is done and a value is loaded to aURL
}

Related

running AppRTC for ios ,RtcEventLog issue

I would like to add an interface in AppRTCMobile, this interface can start webrtc Call module, in order to achieve the audio call between two phones (LAN, already know both the IP address and port number), but when I run successfully , The software crashes every time an exception occurs when the method is called by RtcEventLog. I do not know if Calling Call is reasonable or not. I sincerely thank you for your help in the absence of a solution.
Below the source code, please help me find the problem.
std::unique_ptr<RtcEventLog> event_log = webrtc::RtcEventLog::Create();
webrtc::Call::Config callConfig = webrtc::Call::Config(event_log.get());
callConfig.bitrate_config.max_bitrate_bps = 500*1000;
callConfig.bitrate_config.min_bitrate_bps = 100*1000;
callConfig.bitrate_config.start_bitrate_bps = 250*1000;
webrtc::AudioState::Config audio_state_config = webrtc::AudioState::Config();
cricket::VoEWrapper* g_voe = nullptr;
rtc::scoped_refptr<webrtc::AudioDecoderFactory> g_audioDecoderFactory;
g_audioDecoderFactory = webrtc::CreateBuiltinAudioDecoderFactory();
g_voe = new cricket::VoEWrapper();
audio_state_config.audio_processing = webrtc::AudioProcessing::Create();
g_voe->base()->Init(NULL,audio_state_config.audio_processing,g_audioDecoderFactory);
audio_state_config.voice_engine = g_voe->engine();
audio_state_config.audio_mixer = webrtc::AudioMixerImpl::Create();
callConfig.audio_state = AudioState::Create(audio_state_config);
std::unique_ptr<RtcEventLog> event_logg = webrtc::RtcEventLog::Create();
callConfig.event_log = event_logg.get();
g_call = webrtc::Call::Create(callConfig);
g_audioSendTransport = new AudioLoopbackTransport();
webrtc::AudioSendStream::Config config(g_audioSendTransport);
g_audioSendChannelId = g_voe->base()->CreateChannel();
config.voe_channel_id = g_audioSendChannelId;
g_audioSendStream = g_call->CreateAudioSendStream(config);
webrtc::AudioReceiveStream::Config AudioReceiveConfig;
AudioReceiveConfig.decoder_factory = g_audioDecoderFactory;
g_audioReceiveChannelId = g_voe->base()->CreateChannel();
AudioReceiveConfig.voe_channel_id = g_audioReceiveChannelId;
g_audioReceiveStream = g_call->CreateAudioReceiveStream(AudioReceiveConfig);
g_audioSendStream->Start();
g_audioReceiveStream->Start();
Here's a screenshot of the error that occurred when the crash occurred. Please tell me if you want to know more.
Your code crashed at event_log_->LogAudioPlayout()...
It's obviously that event_log_ object is already released.
Objects which are managed by unique_ptr or scoped_refptr will be released after execution, but these objects may still be used in your case, that will lead to crash problem. So put these objects in global memory or retain them.

cloudkit error no authToken received for asset

Why do I get this error when I run the following code? :
"Internal Error" (1/1000); "No authToken received for asset"
I think it has something to do with the setObject code in the last line.
let documentsDirectoryPath:NSString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
var imageURL: URL!
let imageData = UIImageJPEGRepresentation(self.newImage, 1.0)
let path:String = documentsDirectoryPath.appendingPathComponent(self.newImage.description)
try? UIImageJPEGRepresentation(self.newImage, 1.0)!.write(to: URL(fileURLWithPath: path), options: [.atomicWrite])
imageURL = URL(fileURLWithPath: path)
try? imageData?.write(to: imageURL, options: [.atomicWrite])
let imageAsset:CKAsset? = CKAsset(fileURL: URL(fileURLWithPath: path))
curImages = record["Images"] as! [CKAsset]
curImages.append(imageAsset!)
print("saving image")
record.setObject(curImages as CKRecordValue?, forKey: "Images")
I've encountered this, too. It appears to be a bug in cloudkit, and--from what I can tell--it happens when you try to re-use any part of the "asset creation chain."
In other words, you have some initial data, you create an image from that data, you write it to a file, you load that file into a CKAsset, then you load the CKAsset into the CKRecrod. In my experiments, if you re-use any of those components... or if they just happen to be the same (that is, you create an image, then you happen to create a new-but-identical image later) you'll see this error.
For example, the following code reliably recreates the "no auth token" error when saving a record. All it does is create an array of assets and places it into the record:
for (int i = 0; i <= maxPlayers; i++)
{
int tempVal = 0xf;
NSData *tempData = [[NSData alloc] initWithBytes:&tempVal length:sizeof(tempVal)];
NSString *tempDataFilepath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"temp%d.dat",i]];
[tempData writeToFile:tempDataFilepath atomically:YES];
NSURL *tempDataURL = [NSURL fileURLWithPath:tempDataFilepath];
someArray[i] = [[CKAsset alloc] initWithFileURL:tempDataURL ];
}
someRecord[SOME_FIELD_NAME] = someArray;
Simply changing the third line to:
int tempVal = i; //force the temp value to be different every time
Completely solves the error.
Furthermore, this error occurs even when I tried to use a value in a different CKAsset **that was already used in a prior CKAsset For example, using int tempVal = 0xf in the first asset, then using int secondTempVal = 0xf in another CKAsset also produces the "no auth token" error.
In my case, I was able to force the asset value to always be a unique value, and completely solved the problem. In your case, I suggest the following possible work arounds:
Check if you're using identical images for your assets. If you are, try slightly modifying the images for each new CKAsset.
If you must re-use identical images, try saving the record after you set each asset. I do not know if that will solve the issue, and it certainly increases your network traffic. But it's worth an experiment to see if it helps.
In this question Saving CKAsset to CKRecord in CloudKit produces error: "No authToken received for asset" the OP was able to create separate copies of the image file that ultimately solved the problem.
Open a bug with Apple. I didn't bother doing this, as I've grown jaded watching similar bug reports sit open for years without attention. But who knows, you might have better luck.
This is not an answer to the specific problem (which as been solved by the accepted answer), but it solves another problem that creates the same error message, so it might be useful for somebody else:
I have an app that uses CoreData+Cloudkit with a .public database, i.e. my description for the NSPersistentCloudKitContainer uses
description.cloudKitContainerOptions!.databaseScope = .public
Whenever I change my CloudKit schema, I have to re-initialize it using
do {
try self.initializeCloudKitSchema()
} catch {
print("Could not initialize schema, error \(error)")
}
This creates the error
"Internal Error" (1/1000); "No authToken received for asset"
although I do not use any asset in my model.
I now realized that it has something to do with the .public database:
As soon as I out-comment the instruction that sets the database scope to .public, the re-initialization works without problems.
Now the CloudKit schema is independent of the database type (.private or .public). Thus, a re-initialization of the schema requires the following:
Set the database to .private (the default)
Execute the init code
Set the database to .public
Disable the init code
PS: I know I should write now a bug report, but I stopped doing so: Nearly none of my bug reports (about 15) have ever been answered or processed, so it is not worth the effort.

Save a large number of objects in coredata

I try to save many objects in coredata, but get this crash:
Communications error: <OS_xpc_error: <error: 0x19b354af0> { count = 1, contents =
"XPCErrorDescription" => <string: 0x19b354e50> { length = 22, contents = "Connection interrupted" }
}>
Message from debugger: Terminated due to memory issue
I use MagicalRecord:
[MagicalRecord saveInBackgroundWithBlock:^(NSManagedObjectContext *localContext){
for (int i = 0; i < json.count; i++) {
[Product parseWithData:((NSMutableArray *)json)[i]];
}
}];
Product.m
+ (void)parseWithData:(NSDictionary *)dictionary {
NSString *xml_id = [dictionary[#"XML_ID"] isKindOfClass:[NSString class]] ? dictionary[#"XML_ID"] : #"";
Product *product = [Product getProductWithXML_id:xml_id];
if (!product)
product = [Product MR_createEntity];
product.xml_id = xml_id;
product.code = [dictionary[#"Code"] isKindOfClass:[NSString class]] ? dictionary[#"Code"] : #"";
...
}
Can you suggest me, how can i save it?
When i save my objects in loop to core data - memory grow very fast
It seems to be a memory issue.
Try surrounding the inner part of your for loop with
autoreleasepool {
...
}
You need to paginate the way you get the data and/or save it.
By paginate, i mean :
download the first 1000 (for example, it depends on the content really)
When its done, save the 1000 you just go
When that is done, get the next 1000, save it again, and so on.
You need to know the number you're trying to get and use the (if I remember correctly ) SetLimit: on the parse method, and SetSkip. The skip skips the X first elements, and the limit is the max number of items that will be downloaded.
That way, you skip 0 with limit 1000, then recall the method with skip += limit, and you'll get the second 1000 chunk, and so on. The last chunk will obviously be smaller than 1000.
Doing this will drastically increase the time taken, but that could be done seamlessly in the background ; but it will be spread over much enough to need less memory.
Do it, and see if it makes a big difference. If not, you could always reduce to 500 instead of 1000, or completely change your architecture ; maybe you don't even need ALL the items right now !

Arabic characters (effective power bug) crash my swift iOS app. how do I properly sanitize inputs to avoid this and related problems?

the text that caused the crash is the following:
the error occurred at the following line:
let size = CGSize(width: 250, height: DBL_MAX)
let font = UIFont.systemFontOfSize(16.0)
let attributes = [
NSFontAttributeName:font ,
NSParagraphStyleAttributeName: paraStyle
]
var rect = text.boundingRectWithSize(size, options:.UsesLineFragmentOrigin, attributes: attributes, context: nil)
where text variable contains the inputted string
parastyle is declared as follows:
let paraStyle = NSMutableParagraphStyle()
paraStyle.lineBreakMode = NSLineBreakMode.ByWordWrapping
My initial idea is that the system font can't handle these characters and I need to do an NSCharacterSet, but I'm not sure how to either just ban characters that'll crash my app or make it so i can handle this input (ideal). I don't want to ban emojis/emoticons either.
Thanks!
Not an answer but some information and that possibly provids a way code way to avoid it.
Updated to information from The Register:
The problem isn’t with the Arabic characters themselves, but in how the unicode representing them is processed by CoreText, which is a library of software routines to help apps display text on screens.
The bug causes CoreText to access memory that is invalid, which forces the operating system to kill off the currently running program: which could be your text message app, your terminal, or in the case of the notification screen, a core part of the OS.
From Reddit but this may not be completely correct:
It only works when the message has to be abbreviated with ‘…’. This is usually on the lock screen and main menu of Messages.app.
The words effective and power can be anything as long as they’re on two different lines, which forces the Arabic text farther down the message where some of the letters will be replaced with ‘…’
The crash happens when the first dot replaces part of one of the Arabic characters (they require more than one byte to store) Normally there are safety checks to make sure half characters aren’t stored, but this replacement bypasses those checks for whatever reason.
My solution is the next category:
static NSString *const CRASH_STRING = #"\u0963h \u0963 \u0963";
#implementation NSString (CONEffectivePower)
- (BOOL)isDangerousStringForCurrentOS
{
if (IS_IOS_7_OR_LESS || IS_IOS_8_4_OR_HIGHER) {
return NO;
}
return [self containsEffectivePowerText];
}
- (BOOL)containsEffectivePowerText
{
return [self containsString:CRASH_STRING];
}
#end
Filter all characters to have same directionality. Unfortunately, I'm only aware of such API in Java.
Don't even try. This is a bug in the operating system that will be fixed. It's not your problem. If you try to fix it, you are just wasting your time. And you are very likely to introduce bugs - when you say you "sanitise" input that means you cannot handle some perfectly fine input.
The company I work at develops a multiplatform group video chat.
In Crashlytics report we started noticing that some users are "effectively" trolling iOS users using this famous unicode sequence.
We can't just sit and wait for Apple to fix this bug.
So, I've worked on this problem, this is the shortest crashing sequence I got:
// unichar representation
unichar crashChars[8] = {1585, 1611, 32, 2403, 32, 2403, 32, 2403};
// string representation
NSString *crashString = #"\u0631\u064b \u0963 \u0963 \u0963"
So, I decided to filter out all text messages that contains two U+0963 'ॣ' symbols with one symbol between them (hope you are able to decipher this phrase)
My code from NSString+Extensions category.
static const unichar kDangerousSymbol = 2403;
- (BOOL)isDangerousUnicode {
NSUInteger distance = 0;
NSUInteger charactersFound = 0;
for (NSUInteger i = 0; i < self.length; i++) {
unichar character = [self characterAtIndex:i];
if (charactersFound) {
distance++;
}
if (distance > 2) {
charactersFound = 0;
}
if (kDangerousSymbol == character) {
charactersFound++;
}
if (charactersFound > 1 && distance > 0) {
return YES;
}
}
return NO;
}
Lousy Specta test:
SpecBegin(NSStringExtensions)
describe(#"NSString+Extensions", ^{
//....
it(#"should detect dangerous Unicode sequences", ^{
expect([#"\u0963 \u0963" isDangerousUnicode]).to.beTruthy();
expect([#"\u0631\u064b \u0963 \u0963 \u0963" isDangerousUnicode]).to.beTruthy();
expect([#"\u0631\u064b \u0963 \u0963 \u0963" isDangerousUnicode]).to.beFalsy();
});
//....
});
SpecEnd
I'm not sure if it's OK to "discriminate" messages with too many "devanagari vowel sign vocalic ll".
I'm open to corrections, suggestions, criticism :).
I would love to see a better solution to this problem.

NSInvalidArgumentException / unrecognized selector sent to instance

My app is crashing for some reason after pressing a tableView cell. It doesn't crash the first time but it crashes after couple of time navigating through the table.
Here is my console:
After doing some debugging, if I removed this line of code, it doesn't crash.
[[NSTimeZone localTimeZone] secondsFromGMT] / 30
Here is my viewDidLoad for DetailViewController:
titleLabel.text = [newsArticle objectForKey:#"Series"];
timeLabel.text = [newsArticle objectForKey:#"Duration"];
guestsLabel.text = [newsArticle objectForKey:#"Guests"];
descTextView.text = [newsArticle objectForKey:#"Content"];
"newsArticle" is: NSDictionary variable.
Any ideas why is this happening? Any advice will be appreciated :)
Thanks
As the error message states, you are attempting to basically call setText: with NSNull instead of a string; i.e. [someTextView setText:[NSNull null]];.
Frame #7 is from your app, which is called JSON. So, assuming you are loading a JSON document.
Your JSON document has a NULL value where your code expects there to be a string. Go look at the JSON and figure out where the document contains an unexpected construct.
While fixing your JSON document is part of the solution, I would also suggest hardening your code against such failures.
Found the issue:
There were some items that weren't available on all options so I I used this code to prevent it from crashing and letting the user know that there is no data available:
if (![dictionary objectForKey:#"Guests"] isKindOfClass:[NSNull class]]) {
gueststxt.text = [newsArticle objectForKey:#"Guests"];
} else {
gueststxt.text = #"No Data";
}
Just posted this in case someone comes across this issue.

Resources