How to disable font smoothing in Xcode 9? - ios

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.

Related

Flavouring Objective-C iOS app with Storyboard

I have a single-activity iOS app in Objective-C with Storyboard. The app has two build schemes, say Scheme 1 and Scheme 2. The View has just a couple of buttons. I want to differentiate the color of these button depending on the build scheme.
I am new in the iOS world, but I am having a hard time parametrising the Storyboard (e.g. colors, strings, etc.) depending on the build scheme. I am aware of this post, but I'd like something more explicit.
Thank you for your help.
Conditional compilation with Schemes isn't supported by Xcode. You'd need to maintain two targets instead for that, and that gets messy quickly.
To do this with Schemes you need to maintain two asset catalogs with the correct named colors and copy the correct one in at build time. The source .xcasset catalogs would NOT be added to your target.
You need to add a Run Script early on in the Build Phases section of your target.
Luckily the Scheme name is expressed via the CONFIGURATION environment variable. You could do something like this, your paths might vary:
# Copy over the appropriate asset catalog for the scheme
target=${SRCROOT}/Resources/Colors.xcassets
if [ "${CONFIGURATION}" = "Scheme 1" ]; then
sourceassets=${PROJECT_DIR}/Scheme1.xcassets
else
sourceassets =${PROJECT_DIR}/Scheme2.xcassets
fi
if [ -e ${target} ]; then
echo "Assets: Purging ${target}"
rm -rf ${target}
fi
echo "Assets: Copying source=${sourceassets} to destination=${target}"
cp -r ${sourceassets} ${target}
Essentially you are replacing the compiled version of the asset catalog with one of your Scheme specific versions.
Strings would be another issue and you might be able to do this with the same technique for localised strings.
This all gets horrible very quickly and isn't recommended. Configuring the UI at runtime via code using the technique described in your referenced post would be a better bet.
You could construct a shim layer to protect your code from the Scheme changes.
e.g
#interface MyColors : NSObject
+ (UIColor *)buttonBackground;
#end
#implementation MyColors
+ (UIColor *)buttonBackground {
#if SCHEME1
return [UIColor colorNamed:#"scheme1ButtonBackground"];
#else
return [UIColor colorNamed:#"scheme2ButtonBackground"];
#endif
}
#end

release-debug configuration in React-Native

Currently in React-Native, according to the documentation, to build your iOS app for production, you need to :
change your scheme to Release
change your AppDelegate.m to load the correct bundle
change your Info.pList for ATS
This is a strong violation of 12 factor config recommandation, and it leads to mistakes being made in a continuous integration process.
RN does not provide either out-of-the box strategies to know the configuration environment in the JS code, leading to the existence of the package react-native-config, which does a great job already, but is not perfect (Xcode is not fully supported).
Why is it so? Is it because there are actually so few RN app in production today that nobody cares about this? Can we do better than react-native-config so that steps listed above are not required? I would like a command line that archives my app in the same way that I can run cd android && ./gradlew assembleRelease, without changing anything to my config.
EDIT:
Fastlane makes deployment a lot easier through its gym command (thank you Daniel Basedow). Apparently, the philosophy of Xcode is to call environments "schemes", only you cannot store variables in them, or know which scheme you're running in your code... Anyway, David K. Hess found a great way to export your scheme name in your Info.plist, and then in your Objective C code, which means I'm now able to chose my bundle according to the current scheme, and not touch my code.
Here is my code:
NSString *schemeName = [[[NSBundle mainBundle] infoDictionary] valueForKey:#"SchemeName"];
if ([schemeName isEqualToString:#"scheme1"]) {
jsCodeLocation = [NSURL URLWithString:#"http://localhost:8081/index.ios.bundle?platform=ios&dev=true"];
} else if ([schemeName isEqualToString:#"scheme2"]) {
jsCodeLocation = [NSURL URLWithString:#"http://<my_local_ip_address>:8081/index.ios.bundle?platform=ios&dev=true"];
} else if ([schemeName isEqualToString:#"scheme3"]) {
jsCodeLocation = [[NSBundle mainBundle] URLForResource:#"main" withExtension:#"jsbundle"];
}
Now my problem is : I also want to know which scheme I'm running in my JS code. react-native-config's way is self-described as hacky, and overly complicated considering the fact the information is already in my Objective C code. Is there a way to bridge this information to my JS code?
Only knowing which scheme I'm running is not as good as being able to set environment variables, but at least I'll be able to switch between environments only by changing my scheme.
EDIT 2:
I managed to export my scheme to my JS code. I created a cocoa touch class with the following code:
// RNScheme.h
#import <Foundation/Foundation.h>
#import "RCTBridgeModule.h"
#interface RNScheme : NSObject <RCTBridgeModule>
#end
// RNScheme.m
#import "RNScheme.h"
#interface RNScheme()
#end
#implementation RNScheme
{
}
RCT_EXPORT_MODULE()
- (NSDictionary *)constantsToExport
{
NSString *schemeName = [[[NSBundle mainBundle] infoDictionary] valueForKey:#"SchemeName"];
NSLog(#"%#", schemeName);
return #{
#"scheme_name": schemeName,
};
}
#end
and then in my JS code:
import {NativeModules} from 'react-native'
let scheme = NativeModules.RNScheme.scheme_name
EDIT 3:
There is actually another way than using schemes. You can create new "configurations" ("Release" and "Debug" are called configurations) with the following steps (thanks CodePush):
Open up your Xcode project and select your project in the Project
navigator window
Ensure the project node is selected, as opposed to one of your
targets
Select the Info tab
Click the + button within the Configurations section and select
which configuration you want to duplicate
Then you can define keys with different values according to your configuration.
Select your app target
Chose Build Settings
Go to User-Defined section (at the bottom of the scroll area)
You can define constants with a different value according to your configuration (for instance API_ENDPOINT)
You can then reference this value in your Info.plist file :
Open your Info.plist file
Create a new value and give it a name (ApiEndpoint)
Give it the value $(API_ENDPOINT) or whatever name you gave to your constant
Now you can reference this value in your code using the code I gave you in my second edit to this question.
You can create one scheme per configuration to switch quickly from one to the other, or change the build configuration each time (option click on the run button).
In your AppDelegate you can use the correct bundle like this
#ifdef DEBUG
jsCodeLocation = [NSURL URLWithString:#"http://localhost:8081/index.ios.bundle?platform=ios&dev=true"];
#else
jsCodeLocation = [[NSBundle mainBundle] URLForResource:#"main" withExtension:#"jsbundle"];
#endif
When you do a release build, the DEBUG flag is not set. You can also use different files as your Info.plist depending on build type. There will probably be situations where you want an Xcode debug build with a production JS bundle or vice versa. In that case you need to touch code.
Building ios apps from command line can be a bit tricky. The problems you're describing are not specific to react-native but the Xcode build system. If you haven't already, check out fastlane especially the gym command. It is much simpler than using xcodebuild directly.
But you still have to define your schemes.

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 .........

Duplicate symbols for architecture x86_64 under Xcode

I now have the same question with above title but have not found the right answer yet. I got the error:
/Users/nle/Library/Developer/Xcode/DerivedData/TestMoboSDK-Client-cgodalyxmwqzynaxfbbewrooymnq/Build/Intermediates/TestMoboSDK-Client.build/Debug-iphonesimulator/TestMoboSDK-Client.build/Objects-normal/x86_64/MoboSDK.o
/Users/nle/Library/Developer/Xcode/DerivedData/TestMoboSDK-Client-cgodalyxmwqzynaxfbbewrooymnq/Build/Products/Debug-iphonesimulator/libMoboSDK.a(MoboSDK.o)
duplicate symbol _OBJC_METACLASS_$_MoboSDK in:
/Users/nle/Library/Developer/Xcode/DerivedData/TestMoboSDK-Client-cgodalyxmwqzynaxfbbewrooymnq/Build/Intermediates/TestMoboSDK-Client.build/Debug-iphonesimulator/TestMoboSDK-Client.build/Objects-normal/x86_64/MoboSDK.o
/Users/nle/Library/Developer/Xcode/DerivedData/TestMoboSDK-Client-cgodalyxmwqzynaxfbbewrooymnq/Build/Products/Debug-iphonesimulator/libMoboSDK.a(MoboSDK.o)
ld: 75 duplicate symbols for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Any help is appreciated.
Finally I find out the reason of this error cause I added -ObjC to the Other Linker Flags. After remove this value then I can build my project successfully, but I don't know why. Can anyone explain this?
For me, changing 'No Common Blocks' from Yes to No ( under Targets->Build Settings->Apple LLVM - Code Generation ) fixed the problem.
Stupid one, but make sure you haven't #imported a .m file by mistake somewhere
75 duplicate symbols for architecture x86_64
Means that you have loaded same functions twice.
As the issue disappear after removing -ObjC from Other Linker Flags,
this means that this option result that functions loads twice:
from Technical Q&A
This flag causes the linker to load every object file in the library
that defines an Objective-C class or category. While this option will
typically result in a larger executable (due to additional object code
loaded into the application), it will allow the successful creation of
effective Objective-C static libraries that contain categories on
existing classes.
https://developer.apple.com/library/content/qa/qa1490/_index.html
In my case, I just created a header file to define constant strings like this:
NSString *const AppDescriptionString = #"Healthy is the best way to keep fit";
I solved this scenario by using static:
static NSString *const AppDescriptionString = #"Healthy is the best way to keep fit";
Happens also when you declare const variables with same name in different class:
in file Message.m
const int kMessageLength = 36;
#implementation Message
#end
in file Chat.m
const int kMessageLength = 20;
#implementation Chat
#end
I have same problem.
In Xcode 7.2 in path Project Target > Build Setting > No Common Blocks, i change it to NO.
I found the accepted answer touches on the problem but didn't help me solve it, hopefully this answer will help with this very frustrating issue.
duplicate symbol _OBJC_IVAR_$_BLoginViewController._hud in:
17 duplicate symbols for architecture x86_64
"Means that you have loaded same functions twice. As the issue disappear after removing -ObjC from Other Linker Flags, this means that this option result that functions loads twice:"
In layman's terms this means we have two files in our project with exactly the same name. Maybe you are combining one project into another one? Have a look at the errors above the "duplicate symbols" error to see which folder is duplicated, in my case it was BLoginViewController.
For example, in the image below you can see I have two BImageViewControllers, for me this is what was causing the issue.
As soon as I deleted one then the issue vanished :)
This occurred on me when I accepted "recommended settings" pop-up on a project that I develop two years ago in Objective-C.
The problem was that when you accepted the "recommended settings" update, Xcode automatically changed or added some build settings, including GCC_NO_COMMON_BLOCKS = YES;.
This made the build failed with the duplicate symbol error in my updated project. So I changed No Common Block to NO in my build settings and the error was gone.
I experienced this issue after installing Cocoapods. Now happens everytime I update some pods. Solution I've found:
Go to terminal:
1) pod deintegrate
2) pod install
Also, check the item "Always Embed Swift Libraries" in your Build Settings. It should be "faded" indicating it is using the default configuration. If its set to a manual YES, hit delete over it to revert it to the default configuration. This stopped the behavior.
Fastest way to find the duplicate is:
Go to Targets
Go to Build Phases
Go to Compile Sources
Delete duplicate files.
Go to Targets
Select Build Settings
Search for "No Common Blocks", select it to NO.
It worked for me
Following steps solved the issue for me.
Go to Build Phases in Target settings.
Go to “Link Binary With Libraries”.
Check if any of the libraries exist twice.
Build again.
Remove -ObjC from Other Linker Flags or
Please check you imported any .m file instead of .h by mistake.
Update answer for 2021, Xcode 12.X:
pod deintegrate
pod install
Hope this helps!
My situation with some legacy project opened in Xcode 7.3 was:
duplicate symbol _SomeEnumState in:
followed with list of two unrelated files.o, then this was repeated couple of times, then finally:
ld: 8 duplicate symbols for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
What solved it for me was changing enum declaration from:
enum SomeEnumState {
SomeEnumStateActive = 0,
SomeEnumStateUsed = 1,
SomeEnumStateHidden = 2
} SomeEnumState;
to this:
typedef NS_ENUM(NSUInteger, SomeEnumState) {
SomeEnumStateActive = 0,
SomeEnumStateUsed = 1,
SomeEnumStateHidden = 2
};
If somebody has explanation for this, please enlighten me.
Defining same variable under #implementation in more than one class also can cause this problem.
In my case, there were two file by same name in the location
Targets > Build Phases > Compile Sources and delete any duplicate files.
For me during the Xcode8 recommended project settings update "No Common Blocks" to YES which causes this issue.
My problem was that I had 5 duplicate symbols for architecture x86_64. After reading this post and their answers, I try with the common solution about change GCC_NO_COMMON_BLOCKS = YES to NO
But, instead of working for me, I went from 5 duplicates to 1 duplicate...
So, I paid attention to that last error, and I realized what was my problem, and it was an "incompatibility" with these packages (I had both in package.json):
rn-fetch-blob
react-native-blob-util
The message was clear about it, and I remove rn-fetch-blob because I have not idea why it was in my project, but, I only used with jest and delete it, it wasn't a problem.
So, after removing that package, and run yarn again, problem solved... And without changing the GCC_NO_COMMON_BLOCKS
Today , I got the same error . The error's key word is duplicate. I fix it by:
1. Remove the duplicate file at Build Phases-->Compile Sources
2. If you can not remove it at Build Phases, you need find the file at your project and remove the reference by DELETE :
3. Add the file to your project again
4. Add the file's .m to your Build Phases-->Compile Sources again
5. Build your project, the error will disappear
Another silly mistake that will cause this error is repeated files. I accidentally copied some files twice. First I went to Targets -> Build Phases -> Compile sources. There I noticed some files on that list twice and their locations.
Make sure you haven't imported a .m file by accident, you might want to delete your derived data in the Projects Window and then build and run again.
I got the same error when I added a pod repository
pod 'SWRevealViewController'
for an already added source code (SWRevealViewController) from gitHub. So, the error will be fixed by either removing the source code or pod repository.
Case # 2:
The 2nd time, this error appeared when I declare a constant in .h file.
NSString * const SomeConstant = #"SomeValue";
#interface AppDelegate : UIResponder <UIApplicationDelegate> {
...
...
None of above solutions works for me, I just fixed it myself.
I got duplicate symbol of my core data model which I make it myself, but
in my .xcdatamodeld inspector, I choose Class Definition of Codegen property, I guess that's what's wrong with. Then I choose Manual/None,it got fixed.
Hope this can be helpful for you!
For anyone else who is having this issue, I didn't see my resolution in any of these answers.
After having a .pbxproj merge conflict which was manually addressed (albeit poorly), there were duplicate references to individual class files in the .pbxproj. Deleting those from the Project > Build Phases > Compile Sources fixed everything for me.
Hope this helps someone down the line.
Similar to Juice007, I had declared and initialized a C type variable in two different .m files (that weren't imported!)
BOOL myVar = NO;
however, this method of declaring and initializing a variable, even in .m, even in #implementation grants it global scope. Your options are:
Declare it as static, to limit the scope to class:
static BOOL myVar = NO;
Remove the initialization (which will make the two classes share the global var):
BOOL myVar;
-(void) init{
myVar = NO;
}
Declare it as a property:
#property BOOL myVar;
Declare it as a proper iVar in the #interface
#interface myClass(){
BOOL myVar;
}
#end
In my case I had two main() methods defined in my project and removing one solved the issue.
The answers above didn't work for me. Here's how I got around it:
1) in finder, delete the entire Pods folder and Podfile.lock file
2) close the xcode project
3) run pod install in the terminal
4) open the xcode project, run the clean build command
Worked for me after that.
Because I haven't seen this answer:
Uninstall and reinstall your podfiles! Remove or uninstall library previously added : cocoapods
I've run into this issue over 3 times building my app and every time this is what fixes it. :)
I've just had this error as well. Found that the problem was variables declared with global scope, with the same names, were being repeated throughout the files being compiled into the program. Once changing the global variables to local scope to the pseudo-main function the error was resolved.

string value always shows nil in objective C

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.

Resources