Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Reading this answer about detecting emojis in Swift 5 using unicodeScalars I'm wondering how I can access this in a Objective-C project. I know that Swift-Libs can be accessed in Objective-C, but is there an easier way to access just unicodeScalars and doing something similar to the linked answer?
following the answer it can be changed a little bit to make it work with Bridging back to ObjC..
#objc extension NSString {
var containsEmoji : Bool {
let uni = self as String
for scalar in uni.unicodeScalars {
switch scalar.value {
case 0x1F600...0x1F64F, // Emoticons
0x1F300...0x1F5FF, // Misc Symbols and Pictographs
0x1F680...0x1F6FF, // Transport and Map
0x2600...0x26FF, // Misc symbols
0x2700...0x27BF, // Dingbats
0xFE00...0xFE0F, // Variation Selectors
0x1F900...0x1F9FF, // Supplemental Symbols and Pictographs
0x1F1E6...0x1F1FF: // Flags
return true
default:
continue
}
}
return false
}
}
let's test..
NSString *normal = #"hello world";
NSString *special = #"🏖 badewelt";
if ([special containsEmoji]) {
NSLog(#"emoji inside %#",special);
} else {
NSLog(#"no emoji inside %#",special);
}
// or with dot syntax
if (normal.containsEmoji) {
NSLog(#"emoji inside %#",normal);
} else {
NSLog(#"no emoji inside %#",normal);
}
output
emoji inside 🏖 badewelt
no emoji inside hello world
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
fun sayHello(greet:String,itemsToGreet:List<String>){
itemsToGreet.forEach { itemsToGreet ->
println("$greet, $itemsToGreet")
}
}
fun main() {
val interestingThings = listOf("kotlin","program","comic")
sayHello(greet="hi", interestingThings)
}
A couple of problems:
You can't mix named and positional arguments in a method call. This results in a compilation error.
While not explicitly wrong, the fact that you're shadowing the itemsToGreet variable in your lambda expression is a code smell.
This fixes both:
fun sayHello(greet:String,itemsToGreet:List<String>) {
itemsToGreet.forEach { item -> // new variable name
println("$greet, $item")
}
}
fun main() {
val interestingThings = listOf("kotlin", "program", "comic")
sayHello("hi", interestingThings) // positional arguments
sayHello(greet="hi", itemsToGreet=interestingThings) // named arguments
}
After experimenting with a few little Swift programs, I decided my next step was to port a single module in an Objective-C program into Swift to see what steps were required. I had a number of issues, so I thought I'd post my process and results here in case others might find it useful.
I also created a table to help me remember the different conversions. Unfortunately, StackOverflow doesn't support tables, so I posted these conversions as a Github gist here.
Although Apple will undoubtedly provide an Xcode Refactor to convert from Objective-C to Swift, converting one manually is a great way to get familiar with the differences between the two languages. There is so much 'muscle memory' involved in a language you know well, and this is a great way to get familiar with the new syntax. As promised by Apple, it turns out the languages share so many common ideas, that it's mostly a mechanical process (as opposed to porting from, say C++ or even traditional C).
Note that this process uses none of the exciting new features of Swift, it only gets the code straight across. I should mention that moving to Swift will restrict any backwards compatability to iOS 7 or OS X 10.9. I also ran into a couple of issues (with workarounds below) that I'm sure are just due to the first beta release status of the project, so may not be required in future versions.
I chose iPhoneCoreDataRecipes and picked a module that didn’t rely on a lot of others: IngredientDetailViewController. If you'd like to follow along, check out my "answer" below.
Hope this is of use.
0) Download a copy of the project here and open Recipes.xcodeproj in Xcode version 6.
1) Choose File>New File…>iOS Source>Swift File> IngredientDetailViewController (Folder: Classes, Group: Recipe View Controllers)
2) Reply Yes to “Would you like to configure an Objective-C bridging header?”
3) Copy the first three lines below from Recipes_Prefix.pch and the next three from IngredientDetailViewController.m into Recipes-Bridging-Header.h. If you do further files, obviously don't duplicate lines, and remove any files that you've converted to Swift. I haven't found any where that documents the need for the Cocoa lines, given that they're imported in the swift file, but ...
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
#import "Recipe.h"
#import "Ingredient.h"
#import "EditingTableViewCell.h"
4) Copy/paste the text from both the IngredientDetailViewController.h file and the IngredientDetailViewController.m files into IngredientDetailViewController.swift.
5) Delete both IngredientDetailViewController.h and .m files from project.
6) Do a global Find-and-Replace from #import "IngredientDetailViewController.h" to #import "Recipes-Swift.h" (Only one conversion in this case, and again for further files, don't duplicate this line in your Objective-C modules.)
7) Check the Project>Targets>Recipes>Build Settings Runpath Search Paths. If it shows $(inherited), remove this line or you'll get an error on launch about "no image found"
8) Convert Objective-C syntax in IngredientDetailViewController.swift to Swift. See the GitHub Gist mentioned above the substitutions required, or below for my converted version.
9) You may need to update the IB links. Do a Find>Find in Files on IngredientDetailViewController and select the one in Interface Builder. Open the Identity Inspector in the right-hand column. Select IngredientDetailViewController in the Class field, type xxx or something and tab.
10) Build and Run. Note that after going into a recipe, you must tap Edit and then the info button of an ingredient to activate IngredientDetailViewController
12) Congrats on building your first mixed Swift/Objective-C program!
Here's my cut at this particular module:
``
class IngredientDetailViewController: UITableViewController {
var recipe: Recipe!
var ingredient: Ingredient! {
willSet {
if let newIngredient = newValue {
self.ingredientStr = newIngredient.name
self.amountStr = newIngredient.amount
} else {
self.ingredientStr = ""
self.amountStr = ""
}
}
}
init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
super.init(nibName:nibNameOrNil, bundle: nibBundleOrNil?)
}
init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
}
init(style: UITableViewStyle) {
super.init(style: style)
}
// MARK: table's data source
var ingredientStr: String?
var amountStr: String?
// view tags for each UITextField
let kIngredientFieldTag = 1
let kAmountFieldTag = 2
override func viewDidLoad () {
super.viewDidLoad()
self.title = "Ingredient"
self.tableView.allowsSelection = false
self.tableView.allowsSelectionDuringEditing = false
}
override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return 2
}
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let IngredientsCellIdentifier = "IngredientsCell"
let cell = tableView.dequeueReusableCellWithIdentifier(IngredientsCellIdentifier, forIndexPath: indexPath ) as EditingTableViewCell
if (indexPath.row == 0) {
// cell ingredient name
cell.label.text = "Ingredient"
cell.textField.text = self.ingredientStr
cell.textField.placeholder = "Name"
cell.textField.tag = kIngredientFieldTag
}
else if (indexPath.row == 1) {
// cell ingredient amount
cell.label.text = "Amount"
cell.textField.text = self.amountStr
cell.textField.placeholder = "Amount"
cell.textField.tag = kAmountFieldTag
}
return cell
}
#IBAction func save (sender: AnyObject!) {
if let context = self.recipe.managedObjectContext {
if (!self.ingredient) {
self.ingredient = NSEntityDescription.insertNewObjectForEntityForName("Ingredient",
inManagedObjectContext:context) as Ingredient
self.recipe.addIngredientsObject(self.ingredient)
self.ingredient.displayOrder = self.recipe.ingredients.count
}
// update the ingredient from the values in the text fields
let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow:0, inSection:0)) as EditingTableViewCell
self.ingredient.name = cell.textField.text
// save the managed object context
var error: NSError? = nil
if !context.save( &error) {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate.
You should not use this function in a shipping application, although it may be
useful during development. If it is not possible to recover from the error, display
an alert panel that instructs the user to quit the application by pressing the Home button.
*/
println("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
// if there isn't an ingredient object, create and configure one
self.parentViewController.dismissViewControllerAnimated(true, completion:nil)
}
#IBAction func cancel(sender: AnyObject!) {
self.parentViewController.dismissViewControllerAnimated(true, completion:nil)
}
func textFieldDidEndEditing(textField:UITextField) {
// editing has ended in one of our text fields, assign it's text to the right
// ivar based on the view tag
//
switch (textField.tag)
{
case kIngredientFieldTag:
self.ingredientStr = textField.text
case kAmountFieldTag:
self.amountStr = textField.text
default:
break
}
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
On OS X, a common way of running an application on some files is to drop them on the application bundle in Finder. I need to get the list of those files.
I tried to get them from command arguments (like in Windows), but the command line contains only the program path.
How can I get this list using Qt 5.2 or the Cocoa framework?
To accept files being opened with your application, you need to accept the openFile call for your application delegate, e.g.
- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename
{
NSLog(#"%#", filename);
return YES;
}
Now if you want to accept dragged files onto a window, you have to implement the NSDraggingDestination protocol, there are several answers here about dealing with that API.
Now for Qt, you need to implement the event handler, and deal with the QEvent::FileOpen event, who's parameter is a QFileOpenEvent e.g.
class MyApp : public QApplication
{
protected:
bool event(QEvent *);
};
bool
MyApp::event(QEvent *event)
{
switch (event->type()) {
case QEvent::FileOpen: {
QFileOpenEvent *evt = static_cast<QFileOpenEvent *>(event));
// Do something with event->file() - the file that was opened
return true;
}
default:
return QApplication::event(event);
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How do I create a method in objective-c where I can run the method with different parameters each time. For example I want to be able to do something like this:
int thisMethod (int thisInt; NSString *thisString) {
int anotherInt = thisInt+2;
self.thisLabel.stringValue = thisString;
return 0;
}
So in this code, I want to run thisMethod with two parameters that can be used in the method.
i.e:
thisMethod(10; #"String");
Do I need to use a structure like this:
- (int) thisMethod:(id)sender{
//code here
}
If so, how do I use the parameters?
- (int)thisMethodWithInt:(int)thisInt andString:(NSString *)thisString {
int anotherInt = thisInt+2;
self.thisLabel.stringValue = thisString;
return 0;
}
Calling the Method then would look like this:
[self thisMethodWithInt:3 andString:#"My Super String"];
What you are describing is a c function and not a objective-c one..
You would have to pass the label object too, because self has no meaning in a C function. In Objective-C it's a hidden parameter that is passed to every method, but in a C function you have to pass it yourself (and use commas, instead of semicolons):
int thisMethod (int thisInt, NSString *thisString, id object) {
int anotherInt = thisInt+2;
object.thisLabel.stringValue = thisString;
return 0;
}
You probably have to explicitly set the type though, instead of using id, or the compiler will complain.
Again, use commas to separate arguments:
thisMethod(10, #"String", self);
I know this is a fairly contentious issue amongst programmers, but when developing I like my IDE to position the opening curly bracket underneath the method/interface/control declaration, for illustrative purposes: -
This is how Xcode automatically generates skeleton methods with the { at the end: -
-(void) isTrue:(BOOL)input {
if(input) {
return YES;
}
else {
return NO;
}
}
This is how I like to lay out my code (which I believe is called the Allman style): -
-(void) isTrue:(BOOL)input
{
if(input)
{
return YES;
}
else
{
return NO;
}
}
I'm just wondering if there's any configuration switch in Xcode to enable this style of development? It's really annoying when typing out if/else statements as it tends to auto-complete the else clause with the { at the end of the line which just looks silly if you like developing with them underneath.
Or am I being unreasonable? Is Objective-C supposed to adhere to a standard defined by Apple?
Take a look at:
Xcode: Adjusting indentation of auto-generated braces?
Apple Xcode User Defaults
XCCodeSenseFormattingOptions = {
BlockSeparator = "\\n";
PreMethodDeclSpacing = "";
};
This should at least solve your problem after if, for, or while statements.
After digesting the helpful information from WhirlWind above (thanks), the resulting snippet (just cut and paste into terminal) is:
defaults write com.apple.Xcode
XCCodeSenseFormattingOptions -dict
BlockSeparator "\\n"
PreMethodDeclSpacing ""
Stupid backslash quoting. When typed at the terminal, there should be TWO exactly TWO backslashes in the block separator.
Even with those settings, it does not appear to work with the templates. If you set this and then type "init" in a .m file you get:
- (id)init
{
self = [super init];
if (self) {
<#initializations#>
}
return self;
}
Note the "if (self) {" line.
I believe that "defaults write com.apple.Xcode" doesn't work on the latest versions of Xcode (7.x)
Here are the solutions I know:
Snippet Edit -- this little program will allow to edit default Xcode's code snippets. So, you will be able to open braces from new line in your if, for, while, etc. However, this doesn't allow to change the block indentation.
Uncrustify -- this might solve your problem too, but it doesn't look like being easy to set up. And it only formats the code after it is already written, instead of formatting 'on the go'.