string value always shows nil in objective C - ios

I have upgraded to Xcode 5.0. And when I run an app in debug mode and try to print an NSString value in console, it gives me the below error. Any ideas?
error: warning: couldn't get cmd pointer (substituting NULL): Couldn't load '_cmd' because its value couldn't be evaluated
Couldn't materialize struct: the variable 'stringValue' has no location, it may have been optimized out
Errored out in Execute, couldn't PrepareToExecuteJITExpression
Here is the code:
NSString *stringValue = [[self.responseArray objectAtIndex:i] valueForKey:#"merchant_name"];

The reason is stated in the error message: it may have been optimized out.. this means that you are compiling and running your code in an optimized manner.
you gotta change your compiler optimization level from Fastest,Smallest to none:
go to your target build settings
search for optimization level
change it to none (whatever mode you are in ie debugging, distribution or release)
profit
do the same for your project settings

Make sure you are in debug mode. Go Edit Scheme > Build Configuration > Debug

You might be trying to debug in the "release Scheme". Go to "Product/Scheme/Edit Scheme" and pick the "run" in the left panel. Then change the build configuration to "debug".

One alternate answer: instead of fixing "it may have been optimized out" by removing the optimization, you can stop it from being optimized by using the variable.
So, in your question, if you do something with stringValue:
NSString *stringValue = [[self.responseArray objectAtIndex:i] valueForKey:#"merchant_name"];
NSLog(#"%#", stringValue);
stringValue will no longer be optimized out because you're using it.
If you want to see all instances of optimized-out variables in your project, Use Product -> Analyze to analyze your project. Any "Dead store" warnings (in which a value is stored, and never read) will be optimized out at compile time if you have compiler optimization turned on.

Related

Cannot resolve enum values by name in Xcode debugger

With an enum typedef'd in a global header file used throughout my project, I am unable to refer to the individual enum values by name while using lldb in Xcode.
For example, if I am stopped at a breakpoint anywhere the enum type is available, and I try to evaluate something at the lldb prompt in Xcode (e.g. (lldb) p (int)EnumConstant), lldb complains:
error: use of undeclared identifier 'EnumConstant'
Furthermore, if I try to set a conditional breakpoint using an enum constant in the condition (e.g. right-click breakpoint in Xcode > Edit Breakpoint... > Condition: EnumConstant == someLocalVar), then Xcode complains every time it tries to evaluate that condition at that breakpoint:
Stopped due to an error evaluating condition of breakpoint 1.1: "EnumConstant == someLocalVar"
Couldn't parse conditional expression:
error: use of undeclared identifier 'EnumConstant'
Xcode's code completion popover even resolves a suggestion for the enum constant when I begin typing the name in the "Edit Breakpoint..." window, so Xcode itself doesn't have a problem resolving it.
Is there an option I can set in lldb or Xcode so that lldb maintains the enum identifiers after compilation? I'm assuming the enum constants get translated to their ordinal value during compilation, causing the executable to discard the identifiers, but thats just my naive speculation.
When I use the equivalent code in a simple GNU C program in Linux or Cygwin (minus the class definitions obviously), but using gcc/gdb instead of Xcode/lldb, I don't have these problems. It is able to resolve the enum values no problem.
I've created a tiny Xcode iPhone project to demonstrate what I mean. Using any of the enum_t constants below within the ViewController.m context (the for-loop is a good place to demo) will produce the same results.
ViewController.h:
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
typedef enum
{
eZero, eOne, eTwo, eCOUNT
}
enum_t;
extern NSString const * const ENUM_STR[];
#end
ViewController.m:
#import "ViewController.h"
#implementation ViewController
NSString const * const ENUM_STR[eCOUNT] = { #"eZero", #"eOne", #"eTwo" };
- (void)viewDidLoad
{
[super viewDidLoad];
for (enum_t value = eZero; value < eCOUNT; ++value)
{
NSLog(#"%-8# = %d", ENUM_STR[value], value);
}
}
#end
This is a bug (fairly longstanding) in how the name->Debug Information lookup-accelerator tables for enums are built. While enum types are listed, enum values are not. That was surely done to save output debug info size - debug information gets quite big pretty quickly, and so there's a constant tension between the cost of adding more info and the utility of that more info. So far this one hasn't risen to the level of inclusion.
Anyway, doing a search through "all debug information for anything with a name that matches 'eZero'" is prohibitively slow even for decent sized projects, and gets really bad for large ones. So lldb always uses these name->Debug Info tables for its first level access.
Because the accelerator tables do contain the enum type by name (and more important for you typedefs by name as well), the workaround is to do:
(lldb) expr enum_t::eZero
(int) $0 = 0
Of course, if you have truly anonymous enums, then you are pretty much out of luck till this info gets added to the accelerator tables.
BTW, the Xcode symbol completion in the Debugger Console window is done using the Xcode SourceKit indexer, not lldb. So the completions offered from Xcode are not a reflection of lldb's knowledge of the program.
BBTW, gdb doesn't use compiler-made accelerator tables (these were an Apple extension up till the new DWARF 5 standard) but manually builds an index by scanning the debug info. That allows them to index whatever seems best to the debugger. OTOH, it makes debugger startup quite a bit slower for big projects.

How to disable font smoothing in Xcode 9?

I've got a great programming font Deccy that only looks good with font smoothing (anti aliasing) disabled in Xcode. With Xcode 8 the following would do the trick:
defaults write com.apple.dt.Xcode NSFontDefaultScreenFontSubstitutionEnabled -bool YES
defaults write com.apple.dt.Xcode AppleAntiAliasingThreshold 24
But this no longer works with Xcode 9.
Would it be possible to disable font smoothing in Xcode 9?
Mischief managed?
Here's a screenshot of my Xcode 9 with Deccy at 13pt:
I believe the above is what you want. Here's stock Xcode displaying the same file:
But how?
I probed deep for a noninvasive way to accomplish this, and failed. As far as I can tell, the text rendering path in Xcode 9 very deliberately turns on font smoothing.
Before going any further, please file a feature request with Apple. It only takes a few minutes, and it's your best hope for an answer that that can be discussed in front of those with sound security instincts and strained cardiovasculature:
https://bugreport.apple.com/
I wrote an Xcode plugin. You might have heard that Xcode 9 uses code signing restrictions to forbid the loading of plugins. This is true, but a few mavericks press on, and tonight we ride with them.
Step one
There is a tool, update_xcode_plugins. You can use it to strip the code signature from your copy of Xcode, and with it the bundle-loading restriction:
$ gem install update_xcode_plugins
$ update_xcode_plugins --unsign
If you change your mind, you can do this to revert to (a backup copy, I think?) of signed Xcode:
$ update_xcode_plugins --restore
Step two
There is another tool, Alcatraz. It's a plugin manager for Xcode. I chose to install it because it provides a plugin which provides a project template for plugins. I followed these instructions to install Alcatraz, which boil down to this:
$ git clone https://github.com/alcatraz/Alcatraz.git
$ cd Alcatraz
$ xcodebuild
I launched Xcode, clicked through the dialog warning me about the new plugin, and then used the newly-added Window > Package Manager to install the "Xcode Plugin" template.
Step three
I made a project with this template.
As I write this, the "Xcode Plugin" template hasn't been updated to support Xcode 9. No worries. I ran this command to grab Xcode 9's compatibility UUID:
$ defaults read /Applications/Xcode.app/Contents/Info DVTPlugInCompatibilityUUID
I visited my new project's Info.plist and added that UUID to the DVTPlugInCompatibilityUUIDs array.
Then, I linked SourceEditor.framework into my project. That was a two-step process:
Visit the target's Build Settings. Add this to Framework Search Paths:
/Applications/Xcode.app/Contents/SharedFrameworks/
Visit the target's Build Phases. Add a new "Link Binary With Libraries" phase. Hit the plus. Navigate to the directory above (you can just press the / key and then paste the path in) and choose SourceEditor.framework. It should appear in the list. The project should still build.
Then, I made my plugin's .mm file look like this (I deleted the .h file, it's unneeded for this PoC):
#import <AppKit/AppKit.h>
#include <dlfcn.h>
extern void CGContextSetAllowsFontAntialiasing(CGContextRef, BOOL);
static void hooked_sourceEditorSetFontSmoothingStyle(CGContextRef ctx) {
CGContextSetAllowsFontAntialiasing(ctx, NO);
}
#interface NoAA : NSObject
#end
#implementation NoAA
+ (void)pluginDidLoad:(NSBundle *)plugin
{
NSArray *allowedLoaders = [plugin objectForInfoDictionaryKey:#"me.delisa.XcodePluginBase.AllowedLoaders"];
if (![allowedLoaders containsObject:[[NSBundle mainBundle] bundleIdentifier]])
return;
Class cls = NSClassFromString(#"SourceEditorScrollView");
NSBundle* bundle = [NSBundle bundleForClass:cls];
void *handle = dlopen(bundle.executablePath.fileSystemRepresentation, RTLD_NOW);
if (!handle)
return;
uint8_t* set_font_smoothing_fn = dlsym(handle, "sourceEditorSetFontSmoothingStyle");
if (!set_font_smoothing_fn)
goto fin;
void* set_font_smoothing_fn_page = (void*)((long)set_font_smoothing_fn & -PAGE_SIZE);
if (mprotect(set_font_smoothing_fn_page, PAGE_SIZE, PROT_READ | PROT_WRITE | PROT_EXEC))
goto fin;
set_font_smoothing_fn[0] = 0xe9; // jmp
uint32_t* jmp_arg = (uint32_t*)(set_font_smoothing_fn + 1);
*jmp_arg = (uint32_t)((long)hooked_sourceEditorSetFontSmoothingStyle - (long)(jmp_arg + 1));
mprotect(set_font_smoothing_fn_page, PAGE_SIZE, PROT_READ | PROT_EXEC);
fin:
dlclose(handle);
}
#end
…I think the gotos add character. Basically, it just defines a function that takes a CGContextRef and turns off text antialiasing for it. Then, it overwrites the beginning of a function inside the SourceEditor framework which ordinarily configures antialiasing settings — don't need that anymore — to jump to our function instead. It does all of this in an incredibly unsafe way, so if something goes wrong, Xcode may politely crash.
Build and run the project, which automatically installs the plugin. Accept the addition of your plugin, and that's that.
What now?
If anything here doesn't work because I messed up, let me know. I'm not planning to roll this into an Alcatraz plugin myself, but you or anyone else should free to do so with credit (after filing a feature request with Apple).
Happy hacking!
If you 'live' in XCode and need a crisp rendering of this TrueType font, then editing XCode application defaults with PrefEdit.app, or defaults write com.apple.dt.Xcode.* has no effect.
Thinking outside the box you might be interested in the following to achieve crispyness all-over your Mac.
Since the Deccy font is best viewed at 12pt, it makes sense to raise the AppleAntiAliasingThreshold in the global domain to 13, the default for this setting is 4.
You can also suggest no AppleFontSmoothing.
defaults write -g AppleFontSmoothing -int 0
defaults write -g AppleAntiAliasingThreshold -int 13
In addition to these tweaks a bit more can be achieved in the Accessibility Preference pane in System Preferences: The Display has 2 checkmarks that you should try: 'Differentiate without color', and 'Increase contrast'.
"Beauty is in the eye of the beholder", I hope this helps.
Here are alternative steps that might work for you.
Try to find the com.apple.dt.Xcode.plist file under Macintosh HD/Library/Preferences.
Copy the file to desktop
Open file and add NSFontDefaultScreenFontSubstitutionEnabled to (Boolean)YES
add AppleAntiAliasingThreshold to (Number)24
Replace this file with preference file
Restart the system and Xcode
Note: For safer side keep backup of the original file.

EXC_BAD_ACCESS code=1 because of #{}

I got a EXC_BAD_ACCESS code=1 because of a line like this:
NSDictionary* params = #{};
I didnt create the project, but i notice that have link to a c++ library, and have build setting that is not default (the setting generated by XCode). If i change this line by
NSDictionary* params = [NSDictionary new];
The issue is gone. Can it be something to do with the compiler's setting in project's build setting?
As a comment said this error is likely to be deep in your code. If the culprit is a zombie, the easiest way to find it is to run it (preferably in the latest Xcode, currently Xcode 8, as it has been improved) in profiler and choose "Zombies". When it fails, you can see the history of everything that has happened to the object.
Also, set an exception breakpoint. You may get a break when the error happens instead of in main, where the exception gets passed up.

Show debug messages if argument is set

In my project i'm showing debug messages with global variable:
struct GVariables {
static let debug = false
}
if GVariables.debug {
print("Debug mode enabled")
}
But is it possible to set argument here:
and check debug argument in code. How can i do this ? And is this a correct way ?
You can get access to those launch arguments and environment variables via NSProcessInfo
if NSProcessInfo.processInfo.arguments["DEBUGRPM"] ...
That's not unreasonable and allows you to change the behavior of a compiled app which can be useful in some cases. It does however have some overhead since you're always performing this check. If you would only ever enable debug logging in a debug build then setting a value in "Swift Compiler - Custom Flags" (as shown in the question #Larme linked) and using an #if DEBUGRPM expression will give you conditionally compiled code, saving the app the work of performing a runtime if test.
Which approach is more reasonable for you will depend on how you plan to use and when you plan to toggle this behavior.

Xcode 6.0.1 Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1

I am getting this error on archive:
Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1
How to solve it?
Please see the screenshot.
This problem occurs when the Swift optimization level is not set to None for Release. Set the value to None and the issue goes away.
Open up your project and click on the projects root directory.
Click the build settings tab.
Search for Swift Compiler - Code Generation and under Optimization Level make sure Release is set to None.
EDIT
After upgrading to Xcode 6.1 these instructions caused other issues when archiving (building for debug/device worked fine). Setting the optimization to Fastest allowed me to archive again. There are apparent issues with Swift compiling still (archiving specifically).
Can't archive working 6.0.1 Swift project in Xcode 6.1 / Segmentation fault: 11
EDIT
I was not able to fund the Build Settings tab, until I read this answer.
how to find the build settings tab
This occurred for me when I had two of the exact same files, and also when I was missing I file I didn't know I had deleted. I clicked on the error message, and just above the error, it shows you what file you have more than 1 of or are missing.
You can click the Product in the navigation and choose the "Clean" button; it will clean all compile error in your project. Then, you can debug for the latest error.
Deleted files reference keep in Build Phase and that's why it gives this error. Remove reference from there as well.
Project> Target > Build Phase
Under this section you will find your deleted files in red colour. Remove these files error will resolve.
I am not sure if it has one solution.
I recommend you to check the differences between your last git commit, and comment on/off the changes.
In my case, my code was
let anArray = ResultDict["ResultSet"] as [[NSDictionary : AnyObject]]
for aDict : NSDictionary in anArray {
let anObject = ObjectType(ObjectDict: aDict)
objectList.addObject(aDict)
}
no warning on the line, i got the same exit 1 compile error
then i changed it to the below it has compiled.
let anArray = ResultDict["ResultSet"] as [[NSDictionary : AnyObject]]
for aDict in anArray {
let anObject = ObjectType(ObjectDict: aDict)
objectList.addObject(aDict)
}
I don't know if this is really an answer, but...
I had the same issue. App worked when building/running, but archiving failed with "...swiftc failed with exit code 1", with no other helpful message at all. Luckily, when I tried to build my app with Nomad's ipa build, I got:
The following build commands failed:
CompileSwift normal arm64 /path/to/erroneous/TableViewController.swift
So I started commenting out sections of that file and tracked the problem down to a tuple assignment.
// MARK: - Table Data
private var tableData: [(sectionName: String, item:ListItem)] = []
private func refreshTableData() {
// let labor = ("Labor", laborListItem) // DOESN'T ARCHIVE
let labor = (sectionName: "Labor", item: laborListItem) // ARCHIVES
tableData = [labor]
tableView.reloadData()
}
So apparently the compiler wanted the elements in thast tuple named (as defined by the type of tableData).. but only for archiving? The Dumb thing is, I use this same pattern in other view controllers, and the compiler seems to be fine with those.
For the record my Code Generation -> Optimization Level was set to None for debug and release.
Hope this helps someone! It took hours to figure this out.
It happened to me when I didn't put the parenthesis at the end of a call of a function:
let var = self.getNextPrimeNumber
solved it by:
let var = self.getNextPrimeNumber()
In my case, it was caused by duplicate files, using the same name, in my project directory. As soon as I removed them, the error was gone.
This happened to me when I used static inline function from swift file
The function looks like this
static inline void openURLInSafari(NSString * _Nonnull urlString) {
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:urlString]];}
I just had the same thing occur. I hunted down the cause to one file that caused the error even when empty. Examining the file, I discovered it had the wrong character set. When I set it to UTF-8, the error vanished. I think that it was decoding it with the wrong character set.
From this I surmise that the error simply indicates that something has happened that the compiler was unprepared for. Sorry that isn't very helpful to most people, but it may help to check your characters sets.
one more case that can lead to this error which just took me hours to track down: a failable initializer that always returns nil.
i had an initializer that looked like this:
init?(object: MyObject) {
if object.importantProperty {
// initialize
}
return nil
}
when what i meant was:
init?(object: MyObject) {
if object.importantProperty {
// initialize
}
else {
return nil
}
}
fixing the initializer made the error go away.
If using Core Data:
I had a Core Data entity for which I created the NSManagedObject subclasses (with Xcode's help). In addition, the entity was configured to generate code automatically (see screenshot), so basically 2 classes existed during runtime. Just switch the option to Manual/None and it won't generate it.
This error occurred for me after I noticed that a few of my .swift files were inexplicably in the wrong directory -- one level above my Xcode project directory. When I noticed this, I moved them into the main project directory and cleaned the project, thinking everything would be fine. However, upon building the project I got the above-mentioned "failed with exit code 1" error. Just above the error message it listed the files I had just moved, indicating that it couldn't find them in the directory where they used to be. In addition to the error message, the files I moved were now showing up as red in the file navigation pane.
For each of the files in question what I did to resolve this was:
- Select the file from the list of files in the Xcode file navigation pane,
- Click on the little page icon in the rightmost pane of Xcode, which opens a file attributes pane,
- Click on the little folder icon underneath where it says "Location" in the file attributes pane,
- Choose the new location for the file,
- RESTART Xcode for the above changes to really do anything.
this error comes from missing files so the compiler couldn't find the files and keep alerting.
Follow these steps to rebuild your app:
Look up for the red and invisible files within workspace
Remove their reference
Re-add files
Re-compile
I experienced this error after performing a git merge. I solved new Xcode warnings and the project can be compiled.
Xcode 7.2.1 is used in my case.
In my way the error was due to UIDevice.currentDevice() in ((UIDevice.currentDevice().systemVersion as NSString).floatValue >= 8.0)
After commenting this all starts work fine.
XCode 7.2
in my case , at your project target Build Setttings, in Other Swift Flags,jsut delete the String "-serialize-debuggin-options"
enter image description here
I had a resolution very similar to RyanM, where with an excess of hubris I tried to assign a variable to the default value of an inner function:
Fails to compile (though does not crash SourceKit):
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
func itemCell(_ indexPath: IndexPath = indexPath) -> UITableViewCell {//...}
Succeeds:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
func itemCell(_ indexPath: IndexPath) -> UITableViewCell {//...}
One possible reason that this can happen is perhaps because you have deleted a file but not removed references to it. This will mess up the pbxproj file. I would check to see if that is the case.
check "Development Pods" Folder all listed Frameworks path.
In my case swift development snapshot was selected instead of xcode 9.2. here are the steps and image.
keep xcode on screen and click on xcode top menu bar.
Than go to toolchains option and check on xcode 9.2. thats it.
Happy Coding!!!
So, I had the above and narrowed it down to a TFS issue with locking the file but only when I pasted or did any other edits besides small copies or manual typing. I noticed the original file would compile, but my edits wouldn't, even though they were syntactic OK. Also related is unable to save document: xcode The document "..." could not be saved
The fix for both was:
Duplicate working version.
Paste fully-merged new code into duplicate.
Copy and paste old file over new one. (I personally just renamed the old one to something else, then pasted duplicate and renamed it, too. Guessing both work since I pasted directly earlier for reverts during tests to see).
Voila. Lazy way to bypass merge-locking issue. Apparently full file-pastes are just fine, while edits aren't. Shared since the other answers don't seem to be as lazy as this. ;)
Note: I am suspecting a non-UTF-8 character made its way somewhere, but pastes worked in older versions so I don't know where, or if relevant.
In my case, the error was the result of missing files that were generated by Xcode. I tried the regular clean Opt+Shift+K and it didn't clean up all the errors. I found a post on the Apple Developer site that recomended going to the Product Menu in Xcode, holding down the opt key, and selecting Clean Build Folder. This appears to be a more comprehensive build as it pops up a modal dialog for you to confirm.
Just go to the "project setting" and click on the "build phaces" after that you will find targets in that u have to delete the test file like my project name "WER" so its showing like this WER&TEST so just delete that and clean ur project and run .........

Resources